Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int main()
{
int a=2;
int a1,a2,a3,a4;
a1 = ++a + a ; // output 6 (OK)
a2 = ++a + a++ ; // output 7 (OK)
a3 = ++a + a++ + a ; // output 11 (OK)
a4 = ++a + a++ + a++ ; //output 11 ( WHY ??? )
printf("\n a1=%d, a2=%d, a3=%d and a4=%d,a1,a2,a3,a4);
return 0;
}

What I have tried:

I want to know how it is display because I know a++ display value of a then increase and ++a increse value of a first then show the value of a. when both are combined together then firstly increse all a then put different values of a and lastly put value ++a place. I want to know Last statement how display. Tell me brifly and step by step with clear meaning.

By - Aman Kumar
Posted
Updated 2-Sep-16 3:44am

Basically, don't do that.
The problem (especially with older languages such as C) is that the exact order in which "things happen" is not defined by the language.
As a result, the compiler writer is at liberty to implement pre- and post- increment and decrement operations as they find convenient - which doesn't necessarily mean "immediately" - it is quite possible that they are done before, during or after the execution of the line.
When you add in that the compiler is at liberty to evaluate it's expression in either left-to-right or right-to-left order (unless forced to by precedence rules) and what value you get is not going to be defined, or even consistent between two compilers, or even two versions of the same compiler, or worse: different depending on optimization!

And it's a PITA to read, which means it's difficult to understand and maintain: separate it into different lines, and let the optimizer sort it out!
 
Share this answer
 
You are in gray zone. In C definition, it is stated that the compiler is allowed to change the order of elements in an expression (and more), and since your expression depend on the order of operations, the result is not predictable. Another compiler will give different results.

Use a debugger and display assembly code generated to see how your code was translated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900