hey...i want to understand how following code works :

int x=1;
printf("%d%d%d",x,++x,x);
OUTPUT:  222

also

int x=1;
printf("%d%d%d",x,++x,x++);
OUTPUT:  221

actually these o/p are produced when i use visual c++ compiler but when i wrote the same commands in turbo c they gave perfectly understandable o/p as 221 and331 respectively...so maybe there is a compiler problem or something...hoping someone can throw more light into this

>hoping someone can throw more light into this
It's quite simple on the surface. Your code is broken. ;) The long answer is that there's no intervening sequence point between the evaluation of function arguments, so you're invoking undefined behavior by modifying x multiple times between sequence points. Both of your compilers are correct, as is the hypothetical compiler that chooses to send a nasty email to your boss instead of printing anything.

hey thanks a lot to both of you for your quick and informative reply....
but i have one more query...according to the article

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

so i guess it perfectly explains why my second statement is undefined;

but what about the first one

printf("%d%d%d",++x,x,x);

why is this undefined..as i am modifying(i am guessing modifying means changing the value only???) X only once here..so can you please explain a little more here...thanks

Because there is no defined relationship between the ++ and the three reads of the variable.

Because there is no defined relationship between the ++ and the three reads of the variable.

ok..thanks..got that argument
cheers :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.