Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is accessing two volatiles in one statement is legal in newer C?

Tags:

c

volatile

c99

iar

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?

like image 724
Dmitry Grigoryev Avatar asked Sep 07 '25 14:09

Dmitry Grigoryev


2 Answers

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.

like image 73
Johan Avatar answered Sep 09 '25 22:09

Johan


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.

like image 32
gnasher729 Avatar answered Sep 10 '25 00:09

gnasher729