What kinds of optimizations does 'volatile' prevent in C++?

后端 未结 8 1831
Happy的楠姐
Happy的楠姐 2020-11-27 17:04

I was looking up the keyword volatile and what it\'s for, and the answer I got was pretty much:

It\'s used to prevent the compiler from o

8条回答
  •  迷失自我
    2020-11-27 17:37

    Unless you are on an embedded system, or you are writing hardware drivers where memory mapping is used as the means of communication, you should never ever ever be using volatile

    Consider:

    int main()
    {
        volatile int SomeHardwareMemory; //This is a platform specific INT location. 
        for(int idx=0; idx < 56; ++idx)
        {
            printf("%d", SomeHardwareMemory);
        }
    }
    

    Has to produce code like:

    loadIntoRegister3 56
    loadIntoRegister2 "%d"
    loopTop:
    loadIntoRegister1 <
    pushRegister2
    pushRegister1
    call printf
    decrementRegister3
    ifRegister3LessThan 56 goto loopTop
    

    whereas without volatile it could be:

    loadIntoRegister3 56
    loadIntoRegister2 "%d"
    loadIntoRegister1 <
    loopTop:
    pushRegister2
    pushRegister1
    call printf
    decrementRegister3
    ifRegister3LessThan 56 goto loopTop
    

    The assumption about volatile is that the memory location of the variable may be changed. You are forcing the compiler to load the actual value from memory each time the variable is used; and you tell the compiler that reuse of that value in a register is not allowed.

提交回复
热议问题