0

If I write the code like this below?

int arr[] = {6, 7, 8, 9, 10}; int *ptr = arr; *(ptr++)+= 123; 

what's the elements in the arr[] now?

I originally thougt the arr[] now should be {6, 130, 8, 9, 10}, but actully the result is {129, 7, 8, 9, 10}, I don't know why?

In my opinion, ptr++ is in the bracket, so the ptr should increase first, isn't it? after it increased one, it should point to the second element in the array.

0

4 Answers 4

5

The value of ptr++ is the value of ptr before any increment (the side-effect is incrementing ptr at some time during the evaluation of the expression).

That is the value that is dereferenced in *(ptr++).

If you dereference ptr in a subsequent expression, it points to the next element, the one with value 7.

Sign up to request clarification or add additional context in comments.

Comments

4

Use ++ptr (i.e. pre-increment) if you want the behaviour you're expecting. Parentheses don't affect when the post-increment occurs. In other words, it's nothing to do with precedence.

Comments

0

The basic meaning of ptr++ is First use then Increment that is why it is know as Post Increment Operator. It means that the value of the variable ptr will be updated only when the current instruction has finished execution and the variable is used again in subsequent instructions.

While just the opposite applies for ++ptr is First Increment then use and it is known as Pre Increment Operator.

1 Comment

That's a simplified way of looking at it. ptr++ has a value (the original value of ptr) and a side-effect (increment). When the side-effect occurs in relation to when the value is used is not specified by the language.
0

The effect of this ptr++ will take place only after ';' ptr++ is equivalent to ptr = ptr + 1; but this will done only after semicolon of that statement. ptr value will be arr[0] during the operation *(ptr++)+= 123; but after that statement ptr will be equivalent to arr[1]

1 Comment

If you check the selected and correct answer, it says "the side-effect is incrementing ptr at some time during the evaluation of the expression)". Note "during", not "after".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.