Igor Ševo
Igor Ševo

Reputation: 5525

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?

Upvotes: 4

Views: 292

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106226

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.

Upvotes: 2

Arne
Arne

Reputation: 8509

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.

Upvotes: 7

Related Questions