c++ is not deterministic

12/27/2024
Go back

We are currently reading the C++ standard and project to be done sometime in April.

This brought up something I always knew, but it came to even more light here, that C++ is non-deterministic.

This does not mean that this is so only because of random numbers or the like, but rather, it is built into the program itself, and different compilers (though even the same compiler) are allowed to permit multiple executions for the same program.

int main() { f(g(), h()); }

Here, either g or h can execute first. We can tie this to some specific lines in the standard, some of them here:

Certain other aspects and operations of the abstract machine are described in this document as unspecified behavior (for example, order of evaluation of arguments in a function call ([expr.call])). ... An instance of the abstract machine can thus have more than one possible execution for a given program and a given input.

Interestingly, this is not the same in Java, as outlined in their spec:

Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

This can have real consequences for programs when side effects exist. For example, consider:

f(x++, x);

The following could potentially lead to intended or unintended behavior, but both are valid (and not undefined!) in the realm of C++.

Why? According to Bjarne himself:

Better code can be generated in the absence of restrictions on expression evaluation order.

More to come.