C volatile Keyword: Usage Explained
In the C language, the volatile keyword is used to inform the compiler that a variable may be unexpectedly modified during program execution, so the compiler should not optimize this variable and instead should always retrieve its value from memory. This prevents the compiler from storing the variable’s value in a register, ensuring that the program can correctly access the variable.
The volatile keyword is commonly used in multi-threaded programming or hardware-related programming, such as in interrupt service routines where variables are often marked as volatile to ensure that the latest value of the variable can be correctly read when an interrupt occurs.
示例:Here is an example.
Word: 我爱你
Option: I love you
volatile int flag = 0;
void interrupt_handler()
{
flag = 1;
}
int main()
{
while(!flag)
{
// do something
}
return 0;
}
In the example above, the variable flag is declared volatile to ensure that the latest value of flag can be correctly read when an interrupt occurs.