basic c++ program

hi,
can anyone explain the o/p of this program.

#include<iostream>
using namespace std;
int main()
{
int a=10;
cout<<a<<" "<<a--<<" "<<--a;
return 0;
}
10 10 8
you can simply compile it and see.
a is 10
a-- first returns a and then -- so it prints 10. After that, a is 9.
--a first -- and then returns a. So a is 8 and so prints 8.
cout<<a<<" "<<a--<<" "<<--a; // *** warning: operation on 'a' may be undefined
10 10 8
you can simply compile it and see.


Oh really?
http://ideone.com/JFLSC

As JLB says, you can't say for sure what it will be because the C++ standard does not specify what should happen in this situation.
10 10 9
With g++ 4.4.3, I got

8 9 8
@doug4 --I too got the same o/p( 8 9 8 ).
I do want the explanation.
Actually, i wrote each << as single line and compiled and i get 10 10 8

<code>
cout<<a<<" ";
cout<<a--<<" ";
cout<<--a;
</code>

Here is the explanation for 8 9 8: In C/C++ , you cant modify a variable more than one time per line.(eg. You shouldn't do it: a = --a) So, if you do it, compiler may confuse. Why 8 9 8? http://c-faq.com/expr/evalorder2.html
There is no evaluation order for that modify operators( ++,--,=,+=,-=) in standart.
The link that @tolga gerekci provided sums it up pretty well. As far as this example goes, I can guess as to how it works under the hood.

Before I begin, I want to repeat that the use of multple pre- and post- increment/decrement operators on the same variable (and the naked use of the same variable) within the same line (separated by a ';') is undefined in the standards and different compilers are allowed to handle the situation in different ways. DO NOT USE THIS IN YOUR CODE!

What is probably happening:

The compiler scans the line for pre- operators and finds the pre-decrement in the third location. Because pre- operators happen before a is used, a is decremented (to 9), and the compiler continues to scan.

The compiler scans the line again for post-operators and notices a post-decrement in the second place. Because post-decrement returns the original value, the compiler replaces a in the second position with its value (9) and then decrements a (to 8).

Then the compiler goes about its business of generating the code to do the printing. First it generates code to print a (8), then the value that it substituted in the second step (9), and then, because the pre-decrement already happened, a again (8).

Not all compilers will do it the same way. So NEVER base your code on these side effects. If you want deterministic behavior (hint: you do), separate the print statement into multiple statements like @tolga gerekci did.
Topic archived. No new replies allowed.