Forgot a few of my basics

Aug 5, 2016 at 3:30pm
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.
Aug 5, 2016 at 3:51pm
Can you tell and explain the output of this code.

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

Aug 5, 2016 at 3:59pm
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.
Aug 5, 2016 at 4:01pm
Does that help? :)
Aug 5, 2016 at 5:47pm
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 Aug 5, 2016 at 7:36pm
Aug 5, 2016 at 6:15pm
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 Aug 5, 2016 at 6:23pm
Aug 5, 2016 at 6:32pm
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.
Aug 5, 2016 at 7:33pm
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.
Aug 6, 2016 at 1:44am
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 Aug 6, 2016 at 1:44am
Aug 6, 2016 at 2:23am
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 Aug 6, 2016 at 3:00am
Topic archived. No new replies allowed.