Search code examples
c++constantsqualifiers

Can the compiler not determine whether a variable is const by Itself?


I know for a function this simple it will be inlined:

int foo(int a, int b){
    return a + b;
}

But my question is, can't the compiler just auto-detect that this is the same as:

int foo(const int a, const int b){
    return a + b;
}

And since that could be detected, why would I need to type const anywhere? I know that the inline keyword has become obsolete because of compiler advances. Isn't it time that const do the same?


Solution

  • Yes, the compiler can prove constness in your example.

    No, it would be of no use :-).

    Update: Herb Sutter dedicated one of his gotchas to the topic (http://www.gotw.ca/gotw/081.htm). Summary:

    • const helps most by making the compiler and linker choose functions for const objects including const member functions which can be coded to be more efficient.
    • const doesn't help with the usual translation unit model [differs from what I supposed]; the compiler needs to see the whole program for verifying factual constness (which the mere declaration does not guarantee) and exploiting it, as well as prove the absence of aliasing ...
    • ... and when the compiler can see the whole program and can prove factual constness it actually of course doesn't need the const declaration any longer! It can prove it. Duh.
    • The one place where const makes a big difference is a definition because the compiler may store the object in read-only memory.

    The article is, of course, worth reading.

    With respect to whole program optimization/translation which usually is necessary to exploit constness cf. the comments below from amdn and Angew.