Consider this snippet:
void foo(const int&);
int bar();
int test1()
{
int x = bar();
int y = x;
foo(x);
return x - y;
}
int test2()
{
The const
helps very little to basically nothing for optimization. The compiler basically needs a global view on the code to decide if variables are truly constant or not, and the compiler will determine this regardless of the const
modifiers. Consider this code (e.g. in godbolt.org)
void foo(const int& v) { const_cast(v) = 6; }
const int bar() { return 9; }
int main() {
const int a = bar();
const int b = a;
foo(a);
return a-b;
}
which will result for -O3 in gcc8.3 and clang7 to the very correct and optimal (even with the additional not-essential const_cast
that causes undefined behavior):
foo(int const&): # @foo(int const&)
mov dword ptr [rdi], 6
ret
bar(): # @bar()
mov eax, 9
ret
main: # @main
mov eax, -3
ret
and what is important: this is identical if you replace all const int
by just int
. Thus, it is not the const that helps the compiler, it is global code view and analysis.
In the end let me quote this very interesting GotW page from Herb Sutter http://www.gotw.ca/gotw/081.htm which as I see also started the whole issue.
Thus, const
remains a feature predominately for programmers. Compilers are smarter than us and don't trust us anyway ;-)
And a final remark: optimization is in almost all cases a feature of the compiler and not of the language. There are some exceptions from that, e.g. copy elision
, but the question of this issue is not one of them.