Unknown order of evaluation

There are only four operators in C++ which have a guaranteed evaluation order:

a || b
a && b
a ? b : c
a, b

When the operator is one without a guaranteed evaluation order, a variable being changed twice between two consectutive sequence points creates ill-formed code and unspecified behavior. For example:

int x = 5;
x++ + (x *= 2);

Depending on which side of the addition is evaluated first, the result of the addition could be either 17 or 20, and the value of x afterwards could be either 12 or 11.

What if the expression were the following, though?

x++ + x++;

The standard decrees that the above is unspecified behavior, since x is being changed twice between two sequence points. However, regardless of the evaluation order, the result of the addition will be the same, as will the subsequent result of x. Obviously the label of “unspecified” is only applied to this evaluation-order issue because one cannot know the result of an ambiguous expression. If the result is consistent, though, is the code considered safe to use?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: