Definition
Unspecified behavior is the C standard’s name for behavior where the standard allows two or more possibilities and imposes no requirement on which is chosen in any instance. The implementation, meaning a compiler with its options for a given processor, need not document its choice, and may choose differently at different places in a program or each time the same code runs. The standard’s own example is the order in which the arguments of a function call are evaluated. A correct program must give acceptable results under every allowed choice.
The idea
A program numbers its records with a function next_id, which returns 1 on its first call, 2 on its second, and so on. The call show(next_id(), next_id()) is meant to pass 1 as the first argument and 2 as the second. C does not say which of the two calls of next_id runs first, so a conforming compiler may pass 2 and 1. One compiler passes 1 and 2 every time, the tests pass, and years later a new compiler version or another optimization level passes 2 and 1.
The order is left open so that the compiler can evaluate the arguments in whatever order suits the processor, for example to keep values in registers. Grouping is a separate matter. The source fixes which operator applies to which operands: in a() + b() * c(), the multiplication combines the results of b() and c(). It does not fix which of the three calls runs first. Think of an expression as a recipe that says what to combine, not as a timetable that says when each ingredient is prepared. The picture stops being accurate in one respect: a few operators do carry a timetable, as the next section explains.
How it works
C11, the 2011 edition of the C standard, describes order with three relations between evaluations. An evaluation is the computing of a value or of a side effect, a change to the state of the program such as writing a variable, writing to a file, or calling a function that does so.
Sequenced before: evaluation A is completed before evaluation B begins.
Indeterminately sequenced: A completes before B begins, or B before A, but which one is unspecified. Two function calls in one expression are related this way: they never overlap, but their order is open.
Unsequenced: no order at all; the two evaluations may even overlap.
Apart from the obvious rule that an operator’s operands are computed before its result, the orderings that C imposes inside and between expressions are these:
The operators
&&(logical and),||(logical or),?:(conditional) and the comma operator evaluate their left operand completely, side effects included, before the right operand, or, for?:, before the chosen branch.All arguments of a call, and the expression that names the function, are evaluated before the function’s body starts.
Each full expression, such as an expression statement ending in a semicolon, is completed before the next one starts.
An assignment stores its value after both of its sides have been computed.
Everything else is left open: the two operands of +, *, < and most other operators, the two sides of an assignment, and the arguments of a call among themselves. The commas that separate the arguments of a call are not the comma operator, and they impose no order.
An expression depends on the open order when its operands interfere. Two operands interfere if one of them writes something that the other reads or writes: a variable, a buffer, a file, a log or a hardware register. Writes hidden inside called functions count. Two cases follow.
If the interfering operands are function calls, the calls run one after the other in some order, and the result is the outcome of one of the possible orders. This is unspecified behavior.
If an operand writes a scalar object, a single variable of arithmetic or pointer type, directly in the expression, and another operand reads or writes the same object with no order between them, the behavior is undefined, not merely unspecified (C11 clause 6.5, paragraph 2).
i++ + i++anda[i] = i++are undefined.
To check an expression:
List its operands that the rules above leave unordered.
For each operand, write down what it reads and what it writes, following every function it calls.
If no write of one operand meets a read or a write of another, the order does not matter.
If a write meets a direct access to the same variable in another operand, the expression is undefined; rewrite it.
Otherwise, work out the result for every order, and accept the expression only if every result is acceptable.
To fix an order, split the expression into separate statements that store each result in a named variable.
Worked example
Let a global variable n start at 0, and let two functions change it: f() sets n to n + 1 and returns the new value of n; g() sets n to n * 10 and returns the new value of n. Consider the statement r = f() + g();. The two calls interfere, because both read and write n. Both orders are allowed:
ffirst:fsetsnto and returns 1; thengsetsnto and returns 10. So , andnends at 10.gfirst:gsetsnto and returns 0; thenfsetsnto and returns 1. So , andnends at 1.
The allowed outcomes are with , and with . The statement is not undefined, because each write to n happens inside a function body and the two bodies do not overlap; its behavior is unspecified.
If the program needs the first outcome, it must say so:
int a = f();
int b = g();
r = a + b;
Each semicolon ends a full expression, so f runs before g, and on every conforming compiler.
By contrast, n = 0; r = n++ + n++; modifies n twice in one expression, with no order between the two modifications. That is not a choice between two outcomes. The behavior is undefined, and a compiler may produce any result.
Stated precisely
Clause 3.4.4 of C11 defines unspecified behavior as “use of an unspecified value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance”. Its example is the order in which the arguments to a function are evaluated. An unspecified value (clause 3.19.3) is a valid value of the relevant type where the standard does not say which value is chosen. Annex J.1 lists the unspecified cases.
For function calls that the rules leave unordered among themselves, the allowed results are those of the orders in which the calls can run, where ; for 3 calls that is orders. A sufficient condition for the result to be the same in every order is that no unordered operand writes anything that another unordered operand reads or writes.
Clause 6.5, paragraph 2, draws the line to undefined behavior §4.12: if a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. Clause 6.5.2.2, paragraph 10, makes the execution of a called function’s body indeterminately sequenced with every evaluation in the caller that is not otherwise ordered with it. That is why writes inside two called functions give an unspecified order rather than undefined behavior.
Limits and common mistakes
Unspecified does not mean random. A compiler usually fixes one order for each place in the code when it compiles that place, so a program that depends on the order behaves the same in every test, until the compiler, its version, its options or the surrounding code change. Tests therefore rarely reveal the dependence; reading the code does.
Unspecified is not undefined, but the line is narrow. Every allowed outcome is a normal execution of the program. Moving a write from inside a called function into the expression itself, as from f() + g() to n++ + n++, turns an unspecified order into undefined behavior.
Unspecified is not implementation-defined. Implementation-defined behavior §4.13 is a choice that the compiler must document. For unspecified behavior the compiler need not say which order it chose, and it may choose differently at two places in the same program.
Some values are unspecified too. When a value is stored in a structure, the padding bytes between its members take unspecified values (C11 clause 6.2.6.1, paragraph 6). Comparing two structures with memcmp, which compares raw bytes, can therefore report a difference between equal values, and sending the raw bytes of a structure over a network can leak whatever the padding held.
Other languages decide differently. Java and C# evaluate operands from left to right. C++ before its 2017 edition [453] left the order open much as C does. C++17 orders some operators, for example the left operand of << before the right one, and the right side of an assignment before the left one, but still leaves the order of function arguments unspecified.
Compiler warnings catch only some cases. The warning options -Wsequence-point of the C compiler GCC §12.17 (GNU Compiler Collection; GNU stands for GNU’s Not Unix) and -Wunsequenced of the C compiler Clang report undefined cases such as i++ + i++. They do not report two function calls that interfere through a global variable.
Questions answered
Does an expression depend on an evaluation order the language leaves unspecified?
An expression depends on an unspecified evaluation order when two of its operands that C leaves unordered interfere, meaning one of them writes something that the other reads or writes, such as a variable, a buffer, a log or an output device, including writes made inside the functions they call. C leaves unordered the operands of most operators (such as +, * and =) and the arguments of a function call among themselves. The orderings it does impose are: the left operand of &&, ||, ?: and the comma operator before what follows, all arguments before the body of the called function, and one full expression, such as a statement ending in a semicolon, before the next.
To decide, list the unordered operands, record what each one reads and writes, and look for a write that meets a read or write of another. If there is none, every order gives the same result. If the interfering operands are function calls, the behavior is unspecified: the result is the outcome of one of the possible orders, and the program must accept all of them, or split the expression into separate statements so that the order is fixed. If an operand modifies a variable directly and another operand accesses the same variable with no order between them, as in i++ + i++, the behavior is not merely unspecified but undefined, and the expression must be rewritten.
Related entries: Undefined behavior (UB) (§4.12), Implementation-defined behavior (§4.13), Compiler optimization (§3.39), Struct padding and packing (§4.27). Further reading: [78, 453].