Mandalika's scratchpad [ Work blog @Oracle | My Music Compositions ]

Monday, October 11, 2004

C/C++/Java: ++ unary operator

#include <stdio.h>

int main()
{
int i = 5, j = 5;
int total = 0;

total = ++i + j++;
printf("\ntotal of i & j = %d\n", total);
return(0);
}
What will be the total after the execution of total = ++i + j++ statement? 12?
Let's check the output of this program:
total of i & j = 11
Explanation:
The ++ (increment) operator adds 1 to the value of a scalar operand. ++ can either be placed before or after the operand. If it appears before the operand, the operand is incremented, and then the incremented value is used in the expression. If it appears after the operand, the value of the operand is used in the expression before the operand is incremented

so in our example, total = ++i + j++ is equivalent to the following three expressions:
i = i + 1;
total = i + j;
j = j + 1;
Then simple substitution & math show the final value of total as "11"

PS:
If the operand is a pointer, ++ increments the operand by the size of the object to which it points