What is the use of volatile keyword?

后端 未结 7 995
醉酒成梦
醉酒成梦 2020-12-04 23:05

What is the use of volatile keyword in C/C++? What is the difference between declaring a variable volatile and not declaring it as volatile?

7条回答
  •  孤街浪徒
    2020-12-04 23:11

    Volatile tells to compiler that this value might change and the compiler should not do any optimization on it. An example of it.

    /** port to read temperature **/
    #define PORTBASE 0x40000000
    
    unsigned int volatile * const port = (unsigned int *) PORTBASE; 
    
    for(;;)
    {
      if(*port == 300)
      {
         /** shutdown the system **/
      }
    
    }
    

    If port is not volatile, then the compiler will assume that the value cannot be changed. It will never do the checking if *port == 300. However, the value can be changed based on the sensor. We put volatile to tell compiler that don't do any optimization on it. Thumb rule is when using the memory mapped registers, whose value can change based on the circumstance, then use volatile keyword.

提交回复
热议问题