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