Volatile value for arrays and types

People,

Consider this (disgusting) piece of code:

volatile unsigned long a[1]; unsigned long T; void main(void) { a[0] = 0x6675636b; /* first access of a */ T = *a; *(((char *)a) + 3) = 0x64; /* second access of a */ T = *a; } 

... question: ((char *)a) volatile or non-volatile?

This requires a larger question: should there be a relationship between the two calls of a? That is, a person’s common sense says that there is, but the C99 standard says that volatile things are not aliases, so if ((char *)a) is non-volatile, then the two calls are not aliases, and there is no dependency.

Rather, C99 6.7.3 (paragraph 5) states:

"If an attempt is made to access an object defined using a type with variable qualification, using the value l with a type with non-volatile qualification, the behavior is undefined."

So, when we enter a , is a volatile qualifier applied?

+6
source share
2 answers

If in doubt, run some code :) I cracked some similar (slightly less disgusting) test code (win32 C ++ app in msvs 2k10)

 int _tmain(int argc, _TCHAR* argv[]) { int a = 0; volatile int b = 0; a = 1; //breakpoint 1 b = 2; //breakpoint 2 *(int *) &b = 0; //breakpoint 3 *(volatile int *) &b = 0; //breakpoint 4 return 0; } 

When compiled for release, I am allowed to stop at 2 and 4, but not 1 and 3.

My conclusion is that type defines behavior and 1 and 3 have been optimized. Intuition supports this: otherwise, the compiler would have to keep a list of the types of all memory locations listed as mutable and check each access (hard, ugly), and not just associate it with the identifier type (simpler and more intuitive).

I also suspect that this is specific to the compiler (and possibly a certain flag even inside the compiler) and will be tested on any platform before depending on this behavior.

Actually, scratch this, I’ll just try not to depend on this behavior :)

In addition, I know that you specifically asked about arrays, but I doubt it matters. You can easily crack the same test code for arrays.

+1
source

as you said, its "undefined". This means that demons can come out of your nose. Please adhere to "defined" behaviors as much as possible. The volatile will ask the compiler not to optimize the value, since it is an “important” and critical value that can cause problems if it changes due to various optmization mechanisms. But that’s all he can do.

0
source

All Articles