Evaluating post/pre dec/increment

This is driving me NUTS!!! Why are different online compilers giving my different results for this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int increment();
int x;

int main()
{
	x = 3;
	cout << x << " becomes " << increment() << endl;
	
	return 0;
}

int increment() { return x++; }


Some give the output: 3 becomes 4
While others give: 3 becomes 3.

WHICH ONE IS IT!?!? Why is it different?!
Both Visual Studio and Code::Blocks show this:

4 becomes 3
Why is it different?


Because the order of operations in that chain of << is not defined. I couldn't even work out whether your global variable x is updated before or after you returned from that function.

I wouldn't do it. It's like playing Russian roulette.
Last edited on
Simple tutorial... not really sure in regards to your specific program using it in a function... but here:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int main() {
   int i = 5;
   cout << "The pre-incremented value: " << i;
   while(++i < 10 )
      cout<<"\t"<<i;
   cout << "\nThe post-incremented value: " << i;
   while(i++ < 15 )
      cout<<"\t"<<i;
   return 0;
}


Outputs the following:
1
2
The pre-incremented value: 5       6	 7	8	9	
The post-incremented value: 10     11	12	13	14	15
> Why are different online compilers giving my different results for this code?
Simply put, your code exhibits either unspecified or undefined behaviour.
https://en.wikipedia.org/wiki/Sequence_point

If you're changing x in an expression with anything more complicated than simple assignment, it gets messy in a hurry.

An example I did a long time ago with half a dozen different compilers, and some innocuous (but flawed) code.
https://www.dreamincode.net/forums/topic/177775-comma-operator/page__view__findpost__p__1042539
With C++17, the behaviour is well-defined.

19) In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2 (since C++17)
https://en.cppreference.com/w/cpp/language/eval_order
If that is the case, then, as x appears in that chain before increment(), I would have expected it to output
3 becomes 3
Topic archived. No new replies allowed.