An unexpected behavior was observed when using the postfix addition operator in a printf statement. The code is similar as the one below:
#include <stdio.h>
int main()
{
int array[4] = { 100, 200, 300, 400 };
int i;
int index = 0;
for (i=0; i<4; i++) {
printf("array[%d]: %d\n", index, array[index++]);
}
}
Result:
array[1]: 100
array[2]: 200
array[3]: 300
array[4]: 400
In the printf statement, index
was incremented by 1 before its value was printed on the terminal. I had originally assumed that the former index
value would be printed first and then array[index]
, followed by incrementing the value of index
.
To understand such a behavior, I proposed to think of the postfix operator as the following function:
int postfix_add(int *p) {
int old_value = *p;
*p = *p + 1;
return old_value;
}
Then, the printf statement can be expressed as:
printf("array[%d]: %d\n", index, array[postfix_add(&index)]);
This would indeed explain the result as any function in a function argument should be evaluated first.
But my question is, does C really treat the postfix operator as such?