My understanding of the following code is that ip
is incremented in the second printf
statement; then, the value pointed to by *ip
is retrieved. But the output shows otherwise.
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i[2] = { 1, 4 };
int *ip;
ip = i;
printf("%d\n", *ip);
printf("%d\n", *(ip++));
printf("%d\n", *ip);
return 0;
}
Output:
1
1
4
Then, by changing to the pre-increment operator, ++ip
, the expected result occurred.
Code with pre-increment
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i[2] = { 1, 4 };
int *ip;
ip = i;
printf("%d\n", *ip);
printf("%d\n", *(++ip));
printf("%d\n", *ip);
return 0;
}
Output:
1
4
4
My understanding of operator precedence in C is that the ()
have greater precedence than the *
operator. With that said, why is the post-increment operator, ip++
, not evaluated first - as it is within the ()
.
Regardless of evaluation order, ++ip
increments before returning the new value of ip, while ip++
returns the old value of ip and then increments it. (Or, if you prefer, saves the old value, increments ip, and then returns the old value.)
That is the difference between pre- and post-increment.
In both your examples, the parentheses are redundant.