I ran into an "undefined behaviour" warning with IAR compiler for RL78 (v. 1.40.6) with the following code:
static volatile int x[2] = {1, 2};
int test(){
return x[0]+x[1];
}
Warning[Pa082]: undefined behavior: the order of volatile accesses is undefined in this statement C:\sandbox\test.c 32
The compiler tech note provides an explanation which boils down to two side effects (volatile accesses) being unsequenced.
However, I can see that the code above is no problem for newer compilers like GCC 8. Could someone point me to the change in the standard which makes accessing two volatile variables in a single statement legal?
It is not illegal to access two volatile variables in the same statement but since the standard doesn't specify in which order the operands to the +
operator are evaluated the language does not guarantee a specific ordering of the accesses,
thus x[0]
followed by x[1]
and x[1]
followed by x[0]
are equally correct and the compiler may choose any of them. Since this may not be what the user expects, the IAR compiler issues a warning.
Whether it is legal or not: Accessing a volatile variable could have side effects caused by something outside your code. For example reading x[i] might set all elements of x to the value i.
Now it depends on which one you read first, which is at least unspecified but might be undefined behaviour. Best to remove the unspecified behaviour. Assign x[0] and x[1] to two ints a return their some, and your unspecified behaviour is gone.
Why did one compiler not give a warning: Nobody forces it to.
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