0

i'm doing an online c++ learning course with quiz. The last output line of this snippet is to be determined (comments added by me). Correct answer: 10. My question: why 10 and not 11? Calling a(b) swaps the two variables, so why is the last a.a.b 0 and not 1? / Why does the a.b() in cout not affect the a.a.b?

#include <iostream>
using namespace std;

class classA {
public:
    classA() { st.f = st.p = 1; }
    struct { int f, p; } st;
    int bfunc(void);
};

int classA::bfunc(void) { int x = st.f; st.f = st.p; st.p = x; return x; };

int main()
{
    classA a;
    a.st.f = 0;
    cout << a.st.f << a.st.p << endl; //01
    a.bfunc();
    cout << a.st.f << a.st.p << endl;  //10
    a.bfunc();
    cout << a.st.f << a.st.p << endl; //01
    a.bfunc();
    cout << a.st.f << a.st.p << endl; //10
    cout << a.bfunc() << a.st.p << endl; //10
    return 0;
}
x3ke
  • 1
  • 2
  • 1
    Why is everything named `a` or `b`? Are you trying to obfuscate the code on purpose? – Yksisarvinen Apr 29 '22 at 21:08
  • No, this is how they made their quiz (i suppose to make it extra difficult). I could rename it for your convenience – x3ke Apr 29 '22 at 21:11
  • 1
    "Correct answer: 10". [Really?](https://godbolt.org/z/3d6zqGKqn) – n. m. could be an AI Apr 29 '22 at 21:12
  • This is really confusing to me. The quiz says 10. When i execute it in visual studio it is 10 too. I would have thought 11 was the right answer. Is this compiler dependant? Or what am i doing wrong? – x3ke Apr 29 '22 at 21:17
  • 4
    Have a look at [this post](https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17#:~:text=In%20C%2B%2B17%2C%20it,of%20the%20object%20is%20evaluated). I think this comes down to what order the arguments are evaluated. Pre-c++17 you had no guarantees. From c++17 and forward you will always get 11. – super Apr 29 '22 at 21:25
  • 3
    The right answer is "you cannot predict the output", at least until C++17. In C++17 the answer will be "11". If the quiz tells you correct answer is "10", it's an error in the quiz (and I'd question overall value of that learning source). – Yksisarvinen Apr 29 '22 at 21:26
  • Ok this answers it ,thanks .Visual Studio 2019 (which i was using) uses C++14 as Project Default -> i was getting 10 as answer, the same the quiz marked as "right". @Yksisarvinen please place comment as answer so i can accept it. I will notify the institution responsible for the quiz of this issue. That's a really mean thing to put in a quiz for beginners... but it i guess it wasnt intentional. – x3ke Apr 30 '22 at 12:21

0 Answers0