Jump to content

Output Explanation C++

ichihgo
Int i ,x;I=4;X= ++i + ++i + ++i ;

Output = 19

int i ,x,y,z;i=4;x= ++i ;y= ++i ;z= ++i ;cout<<x+y+z;

Output = 18

 

why ?? 

Link to comment
Share on other sites

Link to post
Share on other sites

The C standard says that a variable should only be assigned at most once between two sequence points. A semi-colon for instance is a sequence point. 

i = i++;i = i++ + ++i;

and so on violate that rule. The standard also says that behavior is undefined and not unspecified. Some compilers do detect these and produce some result but this is not per standard.

 

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf @ 3.4.4

Link to comment
Share on other sites

Link to post
Share on other sites

nevermind.

"Instinct or Rationality; Which will you choose? Enchanted by a superiority complex"

"what you do in spite of internet speed is inspiring. :3" From Cae - 2015

Link to comment
Share on other sites

Link to post
Share on other sites

X = ++i + ++i + ++i;

this piece of code invokes undefined behaviour, so you're not guaranteed to get any consistent result

the problem is that you're modifying the value of i more than once in that single line, but the standard doesn't guarantee anything in doing so. apparently, i is incremented twice (to 6) and those values get summed (12), then i is incremented again (7) and added to the previous result (19)

read more

Link to comment
Share on other sites

Link to post
Share on other sites

It depends on the compiler. It's bad practice to add pre-increments anyway.

Link to comment
Share on other sites

Link to post
Share on other sites

This is that code in assembly
EnchantingAcclaimedBrahmancow.gif

CPU: i7 4770k | GPU: Sapphire 290 Tri-X OC | RAM: Corsair Vengeance LP 2x8GB | MTB: GA-Z87X-UD5HCOOLER: Noctua NH-D14 | PSU: Corsair 760i | CASE: Corsair 550D | DISPLAY:  BenQ XL2420TE


Firestrike scores - Graphics: 10781 Physics: 9448 Combined: 4289


"Nvidia, Fuck you" - Linus Torvald

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×