Pages

Monday, December 18, 2017

All about volatile variable in C

What is volatile keyword in C?
volatile is a data type qualifier in C.

Role of volatile variable in signal handler?
When a variable is declared as volatile, the C compiler does not optimize the code where this variable involves.

It also means that someone might externally change the value of this variable over time, hence do not cache the value of this variable.

In case of interrupt handlers or signal handlers where the counter is dependent is on the incoming data, this counter variables value changes due to external factors like arrival of new data on the port. Hence even though the program did not modified the data, the value of this counter variable changed. Such variable should be declared as volatile variable, so that the C compiler does not optimize the usage of this variable and hence does not pick up the value from the cache.

No comments: