In C++, if value of a variable never gets changed once assigned in whole program VS If making that variable as const , In which case executable code is faster? How compiler optimize executable code in case 1?
-
I could not give a definitive answer, this is quite a broad question. But most time, a non-global variable only written once would be optimized(well... the code affecting that variable obviously) by the compiler in a similar way than a constant variable. – YSC Nov 29 '17 at 09:59
-
3`const` is not about making code faster. It's about making it *safer*. If the variable is `const` the compiler will warn you if you accidentally try to re-assign it later, thus saving you from your own mistake. – Jesper Juhl Nov 29 '17 at 10:06
-
1The compiler can *easily* see if a variable is never assigned to again. If you make it `const` and try to change the value, the compiler will tell you. So it knows. – Bo Persson Nov 29 '17 at 13:06
-
@BoPersson I am not sure compilers can analyze few-millions-lines-of-code project "easily". So sometimes, performance-wise `const` keyword helps, please have a look at an example below: https://stackoverflow.com/a/47550670/7969900 – Andriy Berestovskyy Nov 29 '17 at 16:55
2 Answers
A clever compiler can understand that the value of a variable is never changed, thus optimizing the related code, even without the explicit const
keyword by the programmer.
As for your second, question, when you mark a variable as const
, then the follow might happen: the "compiler can optimize away this const by not providing storage to this variable rather add it in symbol table. So, subsequent read just need indirection into the symbol table rather than instructions to fetch value from memory". Read more in What kind of optimization does const offer in C/C++? (if any).
I said might, because const
does not mean that this is a constant expression for sure, which can be done by using constexpr
instead, as I explain bellow.
In general, you should think about safer code, rather than faster code when it comes to using the const
keyword. So unless, you do it for safer and more readable code, then you are likely a victim of premature optimization.
Bonus:
C++ offers the constexpr
keyword, which allows the programmer to mark a variable as what the Standard calls constant expressions. A constant expression is more than merely constant.
Read more in Difference between `constexpr` and `const` and When should you use constexpr capability in C++11?
PS: Constness prevents moving, so using const too liberally may turn your code to execute slower.

- 71,951
- 46
- 188
- 305
-
1
-
2
-
1A `const` object doesn't have to be a constant expression, so the optimization you mention in the 2nd paragraph need not apply. – juanchopanza Nov 29 '17 at 10:04
-
3I disagree with the premature optimization comment. Regardless of performance gains, OP should use `const` and `constexpr` where applicable anyway. The time invested in this is making the code safer and more readable. – patatahooligan Nov 29 '17 at 10:07
-
-
@patatahooligan I completely rephrased that, what do you think about it now? – gsamaras Nov 29 '17 at 10:10
-
@gsamaras Oh I see. I meant the one starting with "As for your second question". – juanchopanza Nov 29 '17 at 10:26
-
Hmm I see your point @juanchopanza, so suggest I erase the "As for your second question" paragraph, or augment it with the fact that even if the variable is `const`, the optimization might not be applied (which it would in the case of the `constexpr`)? – gsamaras Nov 29 '17 at 10:31
-
I'd also mention that constness prevents moving, so using const too *liberally* may turn out slower ... – Massimiliano Janes Nov 29 '17 at 10:42
-
-
Guys, the question was about **variables**, not objects. The question was about **performance**, not safety. How come we ended up with a set of random thoughts about clever compilers, const expressions, safety and move constructors as the best answer? – Andriy Berestovskyy Nov 29 '17 at 17:02
In which case executable code is faster?
The code is faster in case on using const
, because compiler has more room for optimization. Consider this snippet:
int c = 5;
[...]
int x = c + 5;
If c
is constant, it will simply assign 10 to x
. If c
is not a constant, it depend on compiler if it will be able to deduct from the code that c
is de-facto constant.
How compiler optimize executable code in case 1?
Compiler has harder time to optimize the code in case the variable is not constant. The broader the scope of the variable, the harder for the compiler to make sure the variable is not changing.
For simple cases, like a local variables, the compiler with basic optimizations will be able to deduct that the variable is a constant. So it will treat it like a constant.
if (...) {
int c = 5;
[...]
int x = c + 5;
}
For broader scopes, like global variables, external variables etc., if the compiler is not able to analyze the whole scope, it will treat it like a normal variable, i.e. allocate some space, generate load and store operations etc.
file1.c
int c = 5;
file2.c
extern int c;
[...]
int x = c + 5;
There are more aggressive optimization options, like link time optimizations, which might help in such cases. But still, performance-wise, the const
keyword helps, especially for variables with wide scopes.
EDIT:
Simple example
File const.C:
const int c = 5;
volatile int x;
int main(int argc, char **argv)
{
x = c + 5;
}
Compilation:
$ g++ const.C -O3 -g
Disassembly:
5 {
6 x = c + 5;
0x00000000004003e0 <+0>: movl $0xa,0x200c4a(%rip) # 0x601034 <x>
7 }
So we just move 10 (0xa) to x.
File nonconst.C:
int c = 5;
volatile int x;
int main(int argc, char **argv)
{
x = c + 5;
}
Compilation:
$ g++ nonconst.C -O3 -g
Disassembly:
5 {
6 x = c + 5;
0x00000000004003e0 <+0>: mov 0x200c4a(%rip),%eax # 0x601030 <c>
0x00000000004003e6 <+6>: add $0x5,%eax
0x00000000004003e9 <+9>: mov %eax,0x200c49(%rip) # 0x601038 <x>
7 }
We load c
, add 5 and store to x
.
So as you can see even with quite aggressive optimization (-O3) and the shortest program you can write, the effect of const
is quite obvious.
g++ version 5.4.1

- 1
- 1

- 8,059
- 3
- 17
- 33
-
Modern compilers can figure out when to optimize constants regardless of the use of `const` by the programmer. `const` is purely about safety, not optimizations. Take a look at the LLVM IR that clang produces for example; you'll see that it happily throws out all `const`s that you write, because they are worthless to the optimizer since C++ has things like `mutable` and `const_cast`. – Jesper Juhl Nov 29 '17 at 11:04
-
@JesperJuhl The question was about performance and optimizations, not safety. IMO performance-wise `const` helps in some cases. Sure, const is about safety and yes, compilers can figure out when to optimize constants. But in some cases it is hard for the compiler to analyse all the code and variable usages, so it simply assumes the variable might be changed somewhere in the code. With `const` compiler can optimize constants right away. – Andriy Berestovskyy Nov 29 '17 at 11:52
-
I'm pretty sure you are plain wrong (but would love to be proven wrong). At least, last time I looked at clang the frontend just removed all const in the IR it emitted to the optimizer. Can you point to a concrete, provable, example where a compiler actually optimizes C++ based on `const`? – Jesper Juhl Nov 29 '17 at 15:56
-
@JesperJuhl sure, I have added an example, please have a look. – Andriy Berestovskyy Nov 29 '17 at 16:39
-
2Thanks. Seems there *are* cases where the compiler (at least gcc) will in fact optimize based on const. I was wrong. Downvote removed. Have an upvote instead. – Jesper Juhl Nov 29 '17 at 16:44
-
-
@BoPersson are you sure? Online MSVC 19 2017 compiler generates different code just like GCC: https://godbolt.org/g/E9ws6N – Andriy Berestovskyy Nov 29 '17 at 18:01
-
-
@BoPersson well, it might be just the matter of compiler options... Anyway, by default, most of the compilers will do exactly how I described even with this simple case. Just because the scope of the variable is too broad. So in terms of performance, there are cases where `const` helps... – Andriy Berestovskyy Nov 30 '17 at 13:36