-1

It is my code in the following instruction:

#include <iostream>

using namespace std;

class learning 
{
    public:
        static int func(int var) 
        {
            return var;
        }

        inline bool func(bool var=2 > 1) 
        {
            bool& va = var;
            int num = func(3);
            num += va;
            cout << num << " ";
            return num;
        }
};

int main() 
{
    learning len;
    cout << "Testing " << learning::func(6) << " " << len.func();

    return 0;
}

Why my cmd is print 4 Testing 6 1 but not is Testing 6 1 4?

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
dukan
  • 3
  • 3
  • 1
    Seems like *msvc bug*. The output is `Testing 6 1 4` in gcc and clang. See [demo](https://godbolt.org/z/YzKha45Wv) . But msvc gives `4 Testing 6 1`. – Jason Jan 01 '23 at 03:32
  • 4
    @JasonLiam — not a bug. The 4 comes from inside `func`. The compiler is allowed to call that function before doing the stream insertions. – Pete Becker Jan 01 '23 at 04:50

1 Answers1

4

I believe that what you are seeing is that the order of operator-arguments-evaluation is implementation-specific (at least prior to C++17). For further enlightenment, you might try running this program:

#include <iostream>

using namespace std;

static int DebugFunc(int i)
{
   fprintf(stderr, "DebugFunc called with argument %i\n", i);
   return i;
}

int main()
{
    cout << DebugFunc(1) << DebugFunc(2) << DebugFunc(3);
    return 0;
}

On my compiler (clang++/MacOS), the program outputs this (Note that the "DebugFunc called" lines are fprint()'ed to stderr rather than using cout, to avoid complicating the output of the cout line in main()):

DebugFunc called with argument 1
DebugFunc called with argument 2
DebugFunc called with argument 3
123

... which is reasonable, but I think MSVC is free to evaluate the arguments in a different order, and output e.g. this:

DebugFunc called with argument 3
DebugFunc called with argument 2
DebugFunc called with argument 1
123

If MSVC is evaluating the arguments from right-to-left, that would explain why your program's "4" is printed before its "Testing".

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234