Pre and post increment

void main()
{
int a=1;
printf("%d %d %d",a,++a,a++);
}

How come the output is 3 3 1.Shouldn't the output of the pgm be 2 2 1?
Please help me with this.
If you do something like b=a++;, the compiler assigns b the value of a before increasing a. But if you type b=++a; it increases a before adding it to b.

Sorry for helping out of context because I am not very good at C.
Initially I thought it should be 1 2 2 while reading from left to right .
But seeing the output , it seems the compiler calculates the values from right to left.

a = 1;
b = a++ ;
cout << b ; //should give 1
cout << a ; //should give 2

Thus the value of a++ is printed as 1 but later it is stored as 2 in a .

Then ++a is calculated , which increments a to 3 , then a is printed.
so the output is 3 3 1 .

 
cout << a << ++a << a++ ;

gives the same output
Last edited on
Shouldn't the output of the pgm be 2 2 1?

No.

The program contains an error: a, ++a, and a++ are unsequenced, and since a is a scalar, attempting to execute all three (or, in fact, any two of those three) subexpressions simultaneously results in undefined behavior.

It is the same as accessing an array out of bounds - anything can happen, the program cannot be reasoned about.
+1 @ Cubbi.

This question seems to be coming up more and more.
The program contains an error: a, ++a, and a++ are unsequenced, and since a is a scalar, attempting to execute all three (or, in fact, any two of those three) subexpressions simultaneously results in undefined behavior

@Cubbi ..does this mean that it might give different output each time ?
It means that literally anything at all can happen.

http://www.catb.org/jargon/html/N/nasal-demons.html
Topic archived. No new replies allowed.