#include <stdio.h>
int main()
{
int i = 0;
printf(“i = i++ : %d\n”, i=i++);
printf(“i = %d\n”, i);
return 0;
}
Output is:
0
0
To my understanding i++ returns 0 and it is assigned to i on the left. Thus the value 0 will be printed. But I don’t understand why ‘i’ isn’t incremented then? as it usually does, for example:
Interesting Observation. I ran the code on Ideone.com and got 0 0 but it gave 0 1 when i ran it on Code Blocks on my system. Guess the evaluation is compiler dependent. Here is what i feel is happening
Step 1: Expression on right is evaluated . It is 0.This is stored in some variable temp
Step 2: i is incremented to 1.
Step 3: Value of expression (that was stored in temp) is assigned to i.
As you can see step 3 negates the increment in step 2. I am no expert in compilers nor do i have any idea why this happens. Will have to look at the source code to know exactly but looks like some compilers follow the steps i mentioned above.
Above line of code exhibits undefined behavior. For an LOC(line of code) with undefined behavior, you can not question why, how etc. (Output differs with compiler, differs with time etc)
LOC of interest exhibits undefined behavior because variable i is being updated twice before next sequence point is reached.
Between the previous and next sequence
point an object shall have its stored
value modified at most once by the
evaluation of an expression.
Furthermore, the prior value shall be
read only to determine the value to be
stored.
6.5.16 Assignment operators, §4:
The order of evaluation of the
operands is unspecified. If an attempt
is made to modify the result of an
assignment operator or to access it
after the next sequence point, the
behavior is undefined.
p.s.
Any LOC in C language can show one of 5 behaviors given below:
Well defined: For ex value of i
after i = 2 + 3 * 5;
Implementation dependent: For ex value of sz in size_t sz = sizeof (int);
Unspecified: For ex: Order of evaluation in, add(print(“hi”), print(“Hello”));
Undefined: For ex: value of i afer i = 0; i = i++; [it can be 0 or 1 or 100 or -500]
Locale specific: For example what would be printed when you do printf("\\");
Well, according to my knowledge the reason behind this is that when we perform
i=i++;
a new reference in memory is generated since it’s a post-increment value is first assigned to this new memory.
now variable i (new ) is assigned with value 0 and the old memory location is incremented by 1.
if you had done only i++,
it would have incremented the old value and would have given you value as 1.