Home > Software design >  Why value in pointer not incrementing when I use increment operator
Why value in pointer not incrementing when I use increment operator

Time:02-15

int a=5; int *p=&a; I want to increment the value of a so I tried below two methods but why they are giving different values

why a=*(p) ; is giving 5 but a=*(p) 1; is giving 6

CodePudding user response:

In the line a=*(p) ; the () around p don't do anything and the line is parsed as a = (*(p )); since postfix increment has higher precedence than indirection.

So you are incrementing the pointer, not the variable that the pointer points to. The postfix increment results in the value of the pointer before it was incremented, which you then dereference to give you the current value of a.

Then the line effectively becomes a = a;, doing nothing, except that p now points one-past a.


The line a=*(p) 1; is parsed as a = ((*p) 1); since indirection has higher precedence than addition. This is effectively a = a 1;, doing what you want.


There is however no point in using assignment at all. Just write (*p) ; to increment a through the pointer.

CodePudding user response:

The reason is that postfix operator increments the value after providing it, and prefix operator increments the value before providing it. try a= *(p); instead if you want to assign 6 into a.

  • Related