Reputation: 483
Please be easy on me and don't shoot me as I'm still newbie.
I'm totally confused and can't for life figure out why when I run this code:
int y = 9;
cout << "++y = " << ++y << "\n--y = " << --y << "\ny++ = " << y++ << "\ny-- = " << y-- << "\n";
cout << "y = " << y << "\n";
I get the following results:
y = 9
++y = 9
--y = 9
y++ = 8
y-- = 9
y = 9
instead of these results:
y = 9
++y = 10
--y = 9
y++ = 9
y-- = 10
y = 9
That I get from this code:
int y = 9;
cout << "y = " << y << "\n";
cout << "++y = " << ++y << "\n";
cout << "--y = " << --y << "\n";
cout << "y++ = " << y++ << "\n";
cout << "y-- = " << y-- << "\n";
cout << "y = " << y << "\n";
Can anyone explain -in simple words as possible- what happens in the first code so that it prints the result that way?
Upvotes: 2
Views: 407
Reputation: 1
A simple rule is that you are not expected to increment the same location more than once in any given statement. So you should not code cout << y++ << ++y << endl;
which contain two increments of y
(assuming an int y;
declaration).
For details, read about sequence points and undefined behavior in the C++ standard.
There are lot of related questions. Look into them for more!
Upvotes: 11
Reputation: 24464
When according to the rules operation * is to be counted before +, and ++ before *, it will be so.
a*b++ + c // first b++ (returns **old** b), than a*b, than ...+c
But when you have a++ * a--, nobody can tell, what of the two operands, a++ or a-- will be evaluated the first. According to ANSII standard, even if you use the same translator, the result is every time unpredictable.
cite from the C++ ANSII standard:
Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. Between the previ- ous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Fur- thermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expres- sion; otherwise the behavior is undefined. [Example:
i = v[i++]; // the behavior is undefined
i = 7, i++, i++; // `i' becomes 9
i = ++i + 1; // the behavior is undefined
i = i + 1; // the value of 'i' is incremented
Sequence points:
So, || is a sequence point, but << is not.
Upvotes: 3
Reputation: 577
Mulitiline version of first code should be:
y = 9;
cout << "y-- = " << y-- << "\n";
cout << "y++ = " << y++ << "\n"
cout << "--y = " << --y << "\n"
cout << "++y = " << ++y << "\n"
cout << "y = " << y << "\n";
Upvotes: 2