Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "value++" causes warning but "value+1" doesn't? [duplicate]

The code:

int a = 0;
a = ++a % 5;

causes the warning:

warning: operation on 'a' may be undefined [-Wsequence-point]
a = ++a % 5;
~~^~~~~~~~~

with various compilers such as gcc when compiling with -Wall

Yet this code, works fine?

int a = 0;
a = (a + 1) % 5;

Why is this a warning, and can it safely be ignored?

Wrapping it in brackets etc. doesn't seem to make the warning go away.

Edit: For clarification, I was using C++17 compiler when seeing these warning messages.

like image 712
Hex Crown Avatar asked Dec 18 '22 17:12

Hex Crown


1 Answers

a = ++a % 5;

a is modified two times. Before C++11, this is undefined behavior — it is not specified that the increment is committed before the assignment. Since C++11, the side effect of the pre-increment on the RHS is guaranteed to be evaluated first, and a is guaranteed to be 1.

a = (a + 1) % 5;

Here, a is only modified one time. The resulted a is guaranteed to be 1.


Per comment: operator precedence does not determine the order of evaluation. Although assignment has higher precedence, the order of evaluation is still unspecified (prior to C++11).

like image 52
L. F. Avatar answered Jan 08 '23 08:01

L. F.