3
votes

Can compiler reorder variable setting and throw() op in C++? Or, does standard C++ 14882-1998 allows or prohibit compiler of this transform?

For code:

bool funct()
{
    bool succeeded = false;
    bool res_throw = false;

        try {
            throw("it");
            succeeded = true;
        }
        catch(...) {
            res_throw = true;
        }

        cout << "Result of throw: " << res_throw << endl;
        cout << "succeeded: " << succeeded << endl;

    return succeeded;
}

Can the output be a

Result of throw: true
succeeded: true

The Standard says: "[intro.execution]#7":

modifying an object .. are all side effects, which are changes in the state of the execution environment

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place

Is throw statement a sequence point?

2

2 Answers

4
votes

Yes, there is a sequence point associated with the throw statement, because there is a sequence point at the end of every statement.

So succeeded must remain false in your example.

I don't have the C++98 Standard, but in the C++03 Standard:

1.9p16: There is a sequence point at the completion of each full-expression.

A statement is the simplest kind of "full-expression", but the Standard is worded to include other expressions that are not technically part of any statement.

4
votes

The semicolon is a sequence point. The throw happens before succeeded is set to true

EDIT: To clarify: succeeded will not be set to true