Search code examples
c++variablesmemoryconstantscompiler-optimization

Does the compiler replace constant variables with their value in C++?


Must the processor get constant variables' values from memory every time they are used? If constant variables can't be changed, the compiler can replace them with their values, can't it?


Solution

  • Yes. Any decent compiler will optimize those loads out and just replace them. For example, with Clang 8.0.0 this source code:

    #include <stdio.h>
    const int a = 34;
    
    int main()
    {
        int z = a;
        printf("%d", z);
    }
    

    Gives me this asm:

    main:                                   # @main
            push    rax
            mov     edi, offset .L.str
            mov     esi, 34
            xor     eax, eax
            call    printf
            xor     eax, eax
            pop     rcx
            ret
    .L.str:
            .asciz  "%d"
    

    Notice how a doesn't exist in the asm, only 34 exists.

    In this simple example, a doesn't even have to be const for the compiler to notice it'll never be altered. Removing it would still have the same effect if compiled under optimizations.

    Do note that this is not always the case and thus helping the compiler adding const / constexpr is a good thing to do.