Does a modern C++ compiler ever take const
into account when performing optimizations?
Asked
Active
Viewed 121 times
2

Violet Giraffe
- 32,368
- 48
- 194
- 335
1 Answers
3
If you mark an object as const
, the compiler can infer that it won't ever be modified (although it may have mutable members), and the value of the actual object can be inlined in a lot of places.
Knowing this, if you have something like an if
statement or a loop condition which reads such an object, and the resulting boolean expression is always true or always false, the compiler can therefore eliminate any code branches it knows can't be reached.
Overall, though, the optimizations seem to be pretty negligible when stacked next to the real use case of the const
keyword (code clarity / safety).
You might also want to take a look at this post, because he seems to summarize the possible optimizations in more detail :)

Community
- 1
- 1

yamafontes
- 5,552
- 1
- 18
- 18