Yes it can.
Most const
s are purely for the benefit of the programmer and do not help the compiler optimize because it's legal to cast them away and so they don't tell the compiler anything useful for optimization. However, some const
s cannot be (legally) cast away and these do provide the compiler with useful information for optimization.
As an example, access to a global variable defined with a const
type can be inlined while one without a const
type cannot be inlined because it might change at runtime.
https://godbolt.org/g/UEX4NB
C++:
int foo1 = 1;
const int foo2 = 2;
int get_foo1() {
return foo1;
}
int get_foo2() {
return foo2;
}
asm:
foo1:
.long 1
foo2:
.long 2
get_foo1():
push rbp
mov rbp, rsp
mov eax, DWORD PTR foo1[rip] ; foo1 must be accessed by address
pop rbp
ret
get_foo2():
push rbp
mov rbp, rsp
mov eax, 2 ; foo2 has been replaced with an immediate 2
pop rbp
ret
In practical terms, keep in mind that while const
can improve performance, in most cases it won't or it will but the change will not be noticeable. The primary usefulness of const
is not optimization.
Steve Jessop gives another example in his comment on the original question which brings up something worth mentioning. In a block scope, it's possible for a compiler to deduce if a variable will be mutated and optimize accordingly, regardless of const
, because the compiler can see all uses of the variable. In contrast, in the example above, it's impossible to predict if foo1
will be mutated since it could be modified in other translation units. I suppose a hypothetical sentient ultra-compiler could analyze an entire program and determine if it's valid to inline access to foo1
... but real compilers can't.