0

I have the following code:

#include <iostream>
using namespace std;

class A { 
public: 
    A() { a.a = a.b = 1; }
    struct { int a, b; } a;
    int b(void);
};
int A::b(void) {
    int x = a.a; a.a = a.b; a.b = x; return x;
}
int main(void) { 
    A a;
    a.a.a = 0;
    a.b();
    cout << a.b() << a.a.b << endl;
    return 0;
}

I am getting different result when running in debug mode and in release mode. In release mode i get 11, while in debug mode i get 10. What is causing this output difference? I'm using visual studio 2017.

Laura Maftei
  • 1,863
  • 1
  • 15
  • 25
  • 3
    `cout << a.b() << a.a.b << endl;` smells like undefined behavior to me. It'd be like `cout << i++ << i;` which I believe we have a question on already. Let me see if I can find it... – scohe001 Nov 15 '19 at 20:14
  • 1
    Here are two example questions with good explanatory answers: [1](https://stackoverflow.com/q/33445796/2602718), [2](https://stackoverflow.com/q/5214611/2602718). It looks like convention here is to use the sequence points question as the dupe target though. – scohe001 Nov 15 '19 at 20:15
  • 3
    The order of evaluation of function arguments is unspecified. – rustyx Nov 15 '19 at 20:28

1 Answers1

1

There is an undefined behavior here

cout << a.b() << a.a.b << endl;

The function modifies a.a.b and you read from it too. The compiler can change the other however it wants.

Oblivion
  • 7,176
  • 2
  • 14
  • 33