ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed? (C++17, assume <iostream> and using namespace std)

What is printed? (C++17, assume <iostream> and using namespace std)
struct C {
    int v = 0;
    C& operator++()   { ++v; return *this; }
    C  operator++(int) { C t = *this; ++v; return t; }
};
int main() {
    C c;
    (c++)++;
    ++(++c);
    cout << c.v;
}
  1. A. 3
  2. B. 5
  3. C. 2
  4. D. 4

Correct answer: A. 3

Postfix ++ returns a copy, so (c++)++ increments c once and then a discarded temporary. Prefix ++ returns a reference to c, so ++(++c) adds 2: total 3.

More OOP with C++ and Java questions

Exams that ask this topic