Qualcomm Interview Question
if a variable is preceded with volatile keyword then compiler will try to put the variable in a register to reduce the amount code of loading and storing the variable
volatile is a qualifier of an integer which is just a hint for the compiler to suggest that this piece of storage will be modifies frequently .
Compiler may comply and put it in a CPU register .
It also suggests that the compiler should switch off any optimizations for the variable. i.e if the variable is loaded to a register and the register isn't modified, for the next access of the variable it picks it from the memory instead of using the old register value. (A different thread might have modified the variable)
volatile is the type specifier not the storage specifier. Any variable declared as volatile can be modified by other processes, threads, and some external agents like interrupts without the permission of the declaring process.
Volatile :
A variable that is subjected to change externally is declared with the keyword volatile. By Declaring it volatile , you are informing the compiler to not perform optimization to the part of the code where variable is been used i.e to not rely on the value that is stored in cache for that variable rather go to the memory and get the value for the variable by performing load and store instructions.
Normally the compiler compiles the code in 1/2 passes. i.e. it goes through the code and gives out the corresponding assembly/binary. Code optimization is one of the stage involved in the compilation. At the time of code optimization, the compiler tries to reduce the memory fetch cycles (CPU <----> RAM Read /Write cycles) in order to increase the execution speed of the program when executed. So mostly it is assumed by compiler that a variable is only modified by the CPU operations and no other entity is modifying the variable . So compiler simply removes reading of a frequently used variable from system memory/RAM. But there are cases when the variable allocated in RAM/ System memory is modified by external units such as, in industrial automation various sensors e.g. flow sensor gives out data frequently, once per 10msec. If a variable read of such memory locations are optimized and read only once after program load than sensor data will be erronous. Thus, such memory locations are marked as volatile to avoid any optimization and to read always from the main memory.
- Devendra Vaja December 09, 2012