#include<stdio.h>
void h (int *p) { *p++; }
int main ( )
{
int index = 100;
h(&index);
printf("%d\n",index);
}
This code gives 100 but the one below gives 101 as output. Are not i+=1 and i++ same thing?
#include<stdio.h>
void h (int *p) { *p+=1; }
int main ( )
{
int index = 100;
h(&index);
printf("%d\n",index);
}
>Solution :
It’s all a matter of operator precedence. The complete list is here.
++ has precendence over * (dereferencing), but * has precedence over +=.
Therefore:
*p++ is actually *(p++),
whereas *p+=1 is (*p)+=1.
This means that in the 1st case the increment is done before dereferencing, and has no effect on the passed int (only on the address in the local parameter p).
In the 2nd case the derefrencing is done first and then the increment is performed on the dereferenced value, i.e. the passed int.