Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ exception preventing cout print

In the following code:

#include <iostream>
using namespace std;

int f()
{
    throw 1;
}

int main()
{
    try
    {
        cout << "Output: " << f() << endl;
    }
    catch (int x)
    {
        cout << x;
    }
}

Why isn't "Output: " printed? Shouldn't the operator<<(cout, "Output: ") be called before operator<<(cout, f())? If the line is atomic, how is the printing reversed then?

like image 927
Igor Ševo Avatar asked Jan 09 '23 02:01

Igor Ševo


2 Answers

the order of argument evaluation for the << operator is not defined in the c++ standard. It looks like your compiler evaluates all arguments first, before actually printing.

like image 152
Arne Avatar answered Jan 19 '23 02:01

Arne


It may help to think about the actual operator function calls being assembled as operator<<(operator<<(operator<<(cout, "Output:"), f()), endl): then you can see that operator<<(cout, "Output:") and f() are just two function arguments to another invocation of operator<<: there's no requirement about which function argument is evaluated first.

like image 41
Tony Delroy Avatar answered Jan 19 '23 00:01

Tony Delroy