struggling on the way
struggling on the way

Reputation: 33

operator precedence in C programming language

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.

Upvotes: 0

Views: 416

Answers (4)

Shibin k.reeny
Shibin k.reeny

Reputation: 31

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]

Upvotes: 0

akashbhatia
akashbhatia

Reputation: 332

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.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

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.

Upvotes: 4

pmg
pmg

Reputation: 108968

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.

Upvotes: 5

Related Questions