I newly started working with C and Pointers. There is a concept that confuses me regarding to unary increment operation on pointers.
int num1, *pnum1
num1 = 2;
pnum1 = &num1;
printf("%d \n before: " , *pnum1);
num1 = (*pnum1)++;
printf("%d \n after: " , *pnum1);
return 0;
Since the unary increment operator (++) has greater precedence than the dereference operator (*), I put *pnum1 inside braces. What I expect was to see below result:
after: 3
But it doesn't increment the value of num1. Why would it be the case? Wasn't it suppose to increment the value of num1?
This is undefined behaviour. You're incrementing num1
(via (*pnum1)++
), then assigning the result back to num1
. The order that incrementing and assigning happen is undefined in this case, so it could get the old value of num1
, increment num1
, and then assign the old value back to num1
, which seems to be what your compiler has chosen to do.
If you try num1 = num1++
instead, your compiler will probably warn you about this.
The solution is not to do stuff like this, since it's undefined behaviour.
Look up "sequence points" for more information.