As per the information in this link, post increment and decrement operators have first place. And this link says " Take this example:
foo = *p++;
Here p is incremented as a side effect of the expression, but foo takes the value of *(p++) rather than (*p)++, since the unary operators bind right to left ".
But after doing it practically nothing happened as information mentioned in those links.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i = 1;
int *iptr;
iptr = &i;
int num = *iptr++;//1) In this expression the value of 'i' is assigned to num. And an attempt of post incrementing the address stored in *iptr is done as side effect.
printf("Num value: %d\n",num);
printf("Pointer: %d\n",*iptr);//2) The address of *iptr is not incremented. If it was then the value of 'i' would not be printed instead it would print the incremented address itself.
printf("Post increment: %d\n",*iptr++);//3) The address of *iptr will be post incremented (which didn't happen in case of num). But for now the value of 'i' will be printed.
printf("After increment: %d\n",*iptr);//4) Now the incremented address stored in *iptr will be displayed as there is no value assigned to that address.
return 0;
}
In the above experiment the effect of post increment can be seen only after a statement terminator. But no effect can be seen even after a statement terminator if a post increment is done on the right operand of the assignment operator. E.G int num = *iptr++; (as mentioned in the above experiment). So exactly what place does post increment and decrement operators have in the rules of operator precedence.
The problem with your code is that it has undefined behavior: when you point a pointer to a singular local variable, dereferencing incremented pointer yields undefined behavior.
Derefefencing incremented pointers is well-defined for pointers into an array.
int array[] = {1, 2, 3};
int *iptr = &array[0];
int num = *iptr++;
In addition, printing iptr
using %d
and dereference operator is incorrect: you need to print it using %p
, after casting iptr
to void*
, without dereferencing:
printf("Pointer: %p\n", (void*)iptr);
// No asterisk here -----------^
Now everything works as expected (demo).