Pergunta de entrevista da empresa Arm

volatile and static C keywords

Resposta da entrevista

Sigiloso

1 de mai. de 2011

The volatile keyword, when applied to a variable, tells the compiler not to perform some optimizations to the variable, e.g. temporary keeping its value in a CPU register instead of storing it in the proper memory location. This kind of optimization, even though provides a sensible speed-up (register access is orders of magnitude faster than memory access), can expose the code to inconsistencies if the variable is shared between threads, i.e., it belongs to a critical section. In fact, if the compiler optimizes the program flow such that the value of the variable is temporary stored, upon a context switch another thread might read/write an outdated value. The volatile keyword can be used in other contexts too, e.g. immediately after the "asm" keyword, symbolizing that the inline assembly statement must be kept in the given order of the instruction flow (thus avoiding some "inter-instruction" optimization, like moving a statement out of a loop, or filling a branch delay slot). Regarding the static variable: if applied to a function, it specifies the function is visible only inside the source file it is declared. If applied to a variable, it makes a global variable invisible outside the source file (as a static function), while, for a local variable, it specifies the variable is not automatic, but it is allocated statically, hence the value of the variable will be the same when the function is called again.

4