What is the use of volatile keyword?

后端 未结 7 980
醉酒成梦
醉酒成梦 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 restrict the compiler not to optimize the use of particular variable that is declared volatile in to the code.

    Difference between variable with volatile and without it

    Variable Without volatile

    int main()    
    {    
        int a = 5;
    
        while(a == 5)  //compiler replace variable **'a'** with 5 as optimization purpose    
        {        
        }
    
        if(a==5)//compiler replace **'a'** with 5 as optimization purpose    
        {    
        }
    
        return 0;    
    }
    

    in above code compiler assume that the value of the variable 'a' will always be 5,so compiler replace all 'a' with 5 as optimization purpose.

    Variable with volatile

    But some variables value changed by outside interrupt,so here we always need to get that variables value directly from Memory.For this purpose we use volatile.

    volatile int a=5;
    
    while(a==5) //compiler will npt optimize the variable **'a'** and always get the value of **'a'** from Memory 
    

提交回复
热议问题