-
understanding the volatile keyword in C and why you must know it
03/15/2023 at 12:04 • 1 commentUnderstanding the volatile keyword in C and why embedded engineers must know it
Okey at any embedded interview you will be asked
-What is volatile keyword in C
(standart answer)-volatile tells to compiler not to optimize this variable
but what is optimization and for what compiler should not do that
so what is compiler optimiztion
Compiler optimization is the process of improving the performance and efficiency of compiled code by automatically transforming the source code during compilation. The goal of optimization is to produce faster, smaller, and more efficient code that requires fewer system resources to execute.
Compiler optimization techniques vary depending on the programming language, the compiler, and the target platform. Some common optimization techniques include:
1 Constant Folding: Evaluating constant expressions during compilation and replacing them with their computed values.
2 Loop Unrolling: Replacing a loop with a larger unrolled version that reduces the number of iterations and eliminates some loop overhead.
3 Dead Code Elimination: Removing code that does not contribute to the program output, such as unreachable code or code that produces no side effects.
4 Register Allocation: Assigning variables to CPU registers to reduce the number of memory accesses required during execution.
5 Instruction Scheduling: Reordering instructions to minimize CPU idle time and reduce pipeline stalls.
By applying these and other optimization techniques, compilers can produce faster and more efficient code that runs more efficiently on target platforms.
now what is danger and why we should not have optimized variables in our program
interrupts and ISR we have variable counter and it is updated in our main program and in ISR now the danger is in main program variable(non-volatile) will be saved in register
and written back in it's block of memory after execution so if a ISR will be called before execution it will read not updated value from memory block (.data for example) and the value updated in function that was updated ONLY in register and not in memory block will be lost same thing will happen if we have several threads and both are updating same variable in example with threads everything is a little bit more complicated because we mutexes and threads but anyway cause why we should use volatile keyword is similar
And this process of temporary saving value of variable in register is compiler optimization so using volatile keyword saves us from that optimization and any time our program needs to access volatile variable it goes straight to memory block where variable is saved