0

I am learning a C++. And in this exercise the output in the console is 01, although the a[1] = 0

#include <iostream>

class A
{
public:
    A() { a[0] = 1; a[1] = 0; }
    int a[2];
    int b(void);

};

int A::b(void)
{
    int x = a[0]; 
    a[0] = a[1]; a[1] = x; 
    return x;
}

int main(void)
{
    A a;
    a.b();
    std::cout << a.b() << a.a[1];
    return 0;
}

but if I write the line with cout in two lines like this:

 std::cout << a.b();
 std::cout << a[1];

the output is 00.

  • In `cout << a.b() << a.a[1]`, the order of evaluation of `a.b()` and `a.a[1]` is unspecified (at least before C++17), so an implementation is allowed to do them in any order it likes. When you break that out into two statements, those statements are explicitly sequenced (i.e. `std::cout << a.b()` then `std::cout << a[1]`) – Peter Apr 28 '21 at 15:33
  • What do you expect? you replace the value in `a.b()` and you call it twice that's the normal output. you print `x` which is set in the method `a.b()` – TZof Apr 28 '21 at 15:34
  • 2
    @TZof After C++17 it has to print `00`. Before C++17 the order of evaluation is unspecified and it could result in a different output. Since the question does not specify a language version, there is no "normal output". – François Andrieux Apr 28 '21 at 15:48

0 Answers0