Consider the classical sequence point example:
i = i++;
The C and C++ standards state that the behavior of the above expression is undefined because the = operator is not associated with a sequence point.
What confuses me is that ++
has a higher precedence than =
and so, the above expression, based on precedence, must evaluate i++
first and then do the assignment. Thus, if we start with i = 0
, we should always end up with i = 0
(or i = 1
, if the expression was i = ++i
) and not undefined behavior. What am I missing?
Operator Precedence ¶ The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
Advertisements. Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
All operators produce a result. In addition, some operators, such as assignment operator =
and compound assignment operators (+=
, ++
, >>=
, etc.) produce side effects. The distinction between results and side effects is at the heart of this question.
Operator precedence governs the order in which operators are applied to produce their results. For instance, precedence rules require that *
goes before +
, +
goes before &
, and so on.
However, operator precedence says nothing about applying side effects. This is where sequence points (sequenced before, sequenced after, etc.) come into play. They say that in order for an expression to be well-defined, the application of side effects to the same location in memory must be separated by a sequence point.
This rule is broken by i = i++
, because both ++
and =
apply their side effects to the same variable i
. First, ++
goes, because it has higher precedence. It computes its value by taking i
's original value prior to the increment. Then =
goes, because it has lower precedence. Its result is also the original value of i
.
The crucial thing that is missing here is a sequence points separating side effects of the two operators. This is what makes behavior undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With