Forgot a few of my basics

Ok, I did cote code in c/c++ for about 6 or 7 months. Can you tell and explain the output of this code.

int main()
{
int a=5;
cout<<a++<<" "<<++a<<" "<<a++;
}

i think the output should be 5 7 8.

But it is wrong. can you please explain.
Can you tell and explain the output of this code.

No, you really can't explain undefined behavior it could do anything.

Hi,
The output is 5 7 7

++a immediately increases a by 1 before giving its value to std::cout.
a++ gives its current value to std::cout first for outputing before it increases its value by 1.
Does that help? :)
closed account (E0p9LyTq)
++a immediately increases a by 1 before giving its value to std::cout.
a++ gives its current value to std::cout first for outputing before it increases its value by 1.


There is absolutely ZERO guarantee that the operators will be evaluated in the order you think they will be. Doing multiple increments in a std::cout statement might not evaluate to "5 7 8."

The ONLY guarantee is the final value after the std::cout will be 8 something undefined.
Last edited on
closed account (E0p9LyTq)
Here's the output from Visual C++ 2015 (same as TDM-GCC 4.9.2):

7 8 5


Not even CLOSE to being evaluated in "standard" left-to-right.
Last edited on
The ONLY guarantee is the final value after the std::cout will be 8.


The presented code results in undefined behavior. There are no guarantees.
closed account (E0p9LyTq)
The presented code results in undefined behavior. There are no guarantees.

Ok, you are correct, I was in error. I was being too simplistic. My bad.
There is absolutely ZERO guarantee that the operators will be evaluated in the order you think they will be. Doing multiple increments in a std::cout statement might not evaluate to "5 7 8."

The ONLY guarantee is the final value after the std::cout will be 8 something undefined.



That's crazy! Why is it so unorderly? What happened to order of operations?
Last edited on
closed account (E0p9LyTq)
That's crazy! Why is it so unorderly? What happened to order of operations?

Undefined behavior and sequence points
http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points

more here:

Order of evaluation
http://en.cppreference.com/w/cpp/language/eval_order

There is quite a lot of technical material at those two links.
Last edited on
Topic archived. No new replies allowed.