Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sequence points and operator precedence? 0_o

Tags:

c++

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 ?

like image 486
Mr.Anubis Avatar asked Dec 09 '22 05:12

Mr.Anubis


2 Answers

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.

like image 145
Jon Avatar answered Jan 17 '23 06:01

Jon


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.)

like image 24
CB Bailey Avatar answered Jan 17 '23 05:01

CB Bailey