Reputation: 5312
Let me present a example :
a = ++a;
The above statement is said to have undefined behaviors ( I already read the article on UB on SO)
but according precedence rule operator prefix ++
has higher precedence than assignment operator =
so a
should be incremented first then assigned back to a. so every evaluation is known, so why it is UB ?
Upvotes: 4
Views: 477
Reputation: 1598
It's kind of subtle, but it could be interpreted as one of the following (and the compiler doesn't know which:
a=(a+1);a++;
a++;a=a;
This is because of some ambiguity in the grammar.
Upvotes: 0
Reputation: 791699
Precedence is a consequence of the grammar rules for parsing expressions. The fact that ++
has higher precedence than =
only means that ++
binds to its operand "tighter" than =
. In fact, in your example, there is only one way to parse the expression because of the order in which the operators appear. In an example such as a = b++
the grammar rules or precedence guarantee that this means the same as a = (b++)
and not (a = b)++
.
Precedence has very little to do with the order of evaluation of expression or the order in which the side-effects of expressions are applied. (Obviously, if an operator operates on another expression according to the grammar rules - or precedence - then the value of that expression has to be calculated before the operator can be applied but most independent sub-expressions can be calculated in any order and side-effects also processed in any order.)
Upvotes: 3
Reputation: 437336
The important thing to understand here is that operators can produce values and can also have side effects.
For example ++a
produces (evaluates to) a + 1
, but it also has the side effect of incrementing a
. The same goes for a = 5
(evaluates to 5, also sets the value of a
to 5).
So what you have here is two side effects which change the value of a
, both happening between sequence points (the visible semicolon and the end of the previous statement).
It does not matter that due to operator precedence the order in which the two operators are evaluated is well-defined, because the order in which their side effects are processed is still undefined.
Hence the UB.
Upvotes: 10
Reputation: 39274
Sequence point evaluation #6: At the end of an initializer; for example, after the evaluation of 5 in the declaration int a = 5;. from Wikipedia.
You're trying to change the same variable, a, twice. ++a changes it, and assignment (=) changes it. But the sequence point isn't complete until the end of the assignment. So, while it makes complete sense to us - it's not guaranteed by the standard to give the right behavior as the standard says not to change something more than once in a sequence point (to put it simply).
Upvotes: 1
Reputation: 64223
why it is UB ?
Because it is an attempt to change the variable a
two times before one sequence point:
Upvotes: 1