0

I am observing a weird behavior with this little code :

#include <iostream>
#include <cstdio>

using namespace std;

int get_input()
{
    int val;
    cin >> val;
    return val;
}

int main()
{
    cout << "Res = " << get_input() << "\n";
    //printf("Res = %d\n", get_input());
}

I have compiled it in the simplest way by this command (I have also tried without the -std option):

g++ -Wall -std=c++17 -o test.exe test.cpp

When I execute the code, I see

Res =

in place to have a blank line waiting for the user entry. The behavior that I am expecting is that the "Res = " is displayed after the return of the get_input function. This is the behavior that I observed when I have used a C++ online compiler (like cpp.sh).

Could anyone explain to me what happens here ?

My gcc version on Debian 11 is :

g++ --version
g++ (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Thanks a lot

  • Those operator << invokes aren't doing what you seem to think they are. – WhozCraig Jan 10 '22 at 11:12
  • Also next time please don't describe the output you expect but rather _show_ it. – Jabberwocky Jan 10 '22 at 11:15
  • The linked question explains that the sequence is well-defined for C++17 and onwards. Not sure about pre-C++17, though. Clang-cl (on C++14) doesn't flag any unsequenced operations (which it normally does, when they exist). – Adrian Mole Jan 10 '22 at 11:17

1 Answers1

0

There are two things at play here: Operator precedence and Order of expression-evaluation. Operator precedence in case of << is left-to-right. The Order of evaluation was not defined in previous versions of the compiler; now it is.

As described in this excellent answer, the Order of evaluation is now compatible with Operator precedence, which means it happens left-to-right:

  1. cout << "Res = " happens first. The << operator returns an instance of cout itself.
  2. Then cout << get_input() happens, at which point in time get_input is called. ...and so on.

It used to differ based on the compiler, but now it's standardized.

Sudeep Prasad
  • 91
  • 1
  • 2