0

I'm making some exercises in C++ and in this question, the compilers give me different answers. One gives me 11 and the another one gives me 10, and I don't know which is the correct.

#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 tried to understand the differences but I didn't figure out. It's because in one compiler he reads from left to right and in the another one reads in the other way ?

  • 2
    Which compilers are you using? – xihtyM Mar 15 '23 at 20:15
  • The compilers don't read left to right or vice versa, but they do generate code that *evaluates* left to right or right to left. In this case both are legal until you get to C++17. In that version this code must evaluate left to right. But even in C++17 they are plenty of cases where either a left to right or a right to left order of evaluation are legal. – john Mar 15 '23 at 20:15
  • 2
    `cout << a.b() << a.a.b << endl;` is the same as `cout.operator<<(a.b()).operator<<(a.a.b).operator<<(endl);` and before C++17 the order of evaluation of the function call parameters was indertiminate. – Richard Critten Mar 15 '23 at 20:18
  • 7
    In general this stuff is tricky and the precise behaviour of C++ has changed a couple of times. The only sensible advice is never write code like this. Even if the code is technically correct, it doesn't help anyone trying to follow your code. – john Mar 15 '23 at 20:19
  • 1
    @DrewDormann `a.a = a.b = 1;` is well-defined. `cout << a.b() << a.a.b` is not well-defined until C++17. In earlier versions, whether `a.b()` or `a.a.b` is evaluated first is unspecified. – Remy Lebeau Mar 15 '23 at 20:26

0 Answers0