What is the difference between a static global and a static volatile variable?

后端 未结 7 2038
情歌与酒
情歌与酒 2020-12-08 04:58

I have used a static global variable and a static volatile variable in file scope,

both are updated by an ISR and a main loop and main loop checks the value of the varia

7条回答
  •  难免孤独
    2020-12-08 05:19

    The "volatile" keyword suggests the compiler not to do certain optimizations on code involving that variable; if you just use a global variable, nothing prevents the compiler to wrongly optimize your code.

    Example:

    #define MYPORT 0xDEADB33F
    
    volatile char *portptr = (char*)MYPORT;
    *portptr = 'A';
    *portptr = 'B';
    

    Without "volatile", the first write may be optimized out.

提交回复
热议问题