c++ - Behavior of post increment in cout -


this question has answer here:

#include <iostream> using namespace std;  main(){  int = 5;  cout << i++ << i--<< ++i << --i << << endl;   } 

the above program compiled g++ gives output :

45555 

while following program:

int x=20,y=35;  x =y++ + y + x++ + y++;  cout << x<< endl << y; 

gives result

126  37 

can please explain output.

cout << i++ << i-- 

is semantically equivalent to

operator<<(operator<<(cout, i++),   i--);            <------arg1--------->, <-arg2-> 

$1.9/15- "when calling function (whether or not function inline), every value computation , side effect associated argument expression, or postfix expression designating called function, sequenced before execution of every expression or statement in body of called function. [ note: value computations , side effects associated different argument expressions unsequenced. —end note ]

c++0x:

this means evaluation of arguments arg1/arg2 unsequenced (neither of them sequenced before other).

the same section in draft standard states,

if side effect on scalar object unsequenced relative either side effect on same scalar object or value computation using value of same scalar object, behavior undefined.

now there sequence point @ semicolon @ end of full expression below

operator<<(operator<<(cout, i++), i--);                                       ^ interesting sequence point right here 

as clear, evaluation of both arg1 , arg2 lead side effect on scalar variable 'i', , saw above, side effects unsequenced.

therefore code has undefined behavior. mean?

here how 'undefined behavior' defined :) in standard.

permissible undefined behavior ranges ignoring situation unpredictable results, behaving during translation or program execution in documented manner characteristic of environment (with or without issuance of diagnostic message), terminating translation or execution (with issuance of diagnostic message). many erroneous program constructs not engender undefined behavior; required diagnosed.

do see correlation @darkdust's response 'the compiler allowed set computer on fire :-)'

so output such code in dreaded realm of undefined behavior.

don't it.

only thing defined such code helps op , many of lots of votes (if answered correctly) :)


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -