Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the expression a = a + b - ( b = a ) give a sequence point warning in c++?

Following is the test code:

int main()
{
    int a = 3;
    int b = 4;
    a = a + b - (b = a); 

    cout << "a :" << a << " " << "b :" << b << "\n";    
    return 0;
}

Compiling this gives the following warning:

> $ g++ -Wall -o test test.cpp test.cpp: In function ‘int main()’:
> test.cpp:11:21: warning: operation on ‘b’ may be undefined
> [-Wsequence-point]

Why can the operation be undefined?

According to my understanding, first the subexpression (b = a) should be evaluated because of higher precedence of (), thus setting b = a. Then, since '+' and '-' have same precedence, the expression would be evaluated left-associatively. Thus, a + b should be evaluated next, and finally the result of (b = a) should be subtracted from a + b. I can't see any sequence-point rule being violated here.

like image 918
gjain Avatar asked Nov 09 '12 23:11

gjain


2 Answers

There is a difference between an expression being evaluated and completing its side effects.

The b = a assignment expression will be evaluated ahead of subtraction due to higher precedence of the parentheses. It will provide the value of a as the result of the evaluation. The writing of that value into b, however, may not complete until the next sequence point, which in this case is the end of the full expression. The end result of the overall expression is therefore undefined, because the subtraction may take the value of b before or after the assignment.

like image 149
Sergey Kalinichenko Avatar answered Oct 14 '22 10:10

Sergey Kalinichenko


In C++, subexpressions in arithmetic expressions do not have temporal ordering.

a = x + y;

Is x evaluated first, or y? The compiler can choose either, or it can choose something completely different. The order of evaluation is not the same thing as operator precedence: operator precedence is strictly defined, and order of evaluation is only defined to the granularity that your program has sequence points.

In fact, on some architectures it is possible to emit code that evaluates both x and y at the same time -- for example, VLIW architectures.

like image 45
Dietrich Epp Avatar answered Oct 14 '22 11:10

Dietrich Epp