Compilers can sometime exploit the fact that some ‘variable’ is a constant for optimization, so it’s generally a good idea to use the “const” keyword when you can, but is there a tradeoff?
In short, is there a situation where using “const” might actually make the code slower (even a tiny bit)?
The
constkeyword is used only during compile-time. After the code is compiled the variable is just an address in the memory, without any special protection.There is some difference, however – global
constvariables will be placed in thetextsegment, not thedata(if initialized) or bss (if uninitialized). If thetextsegment is treated differently, for example executed in place from a NOR flash memory (instead of RAM), there might be a difference. Localconstvariables are placed on the stack together with the regular variables, so there should be no difference.Other than that, as bestsss said, some compile time optimizations might be impossible if the variable is a constant. I can’t really think of anything (especially not in pure C), but it is theoretically possible.
Edit:
The following code demonstrated the point in the second paragraph:
}
In Visual Studio 2010, the result is as follows (note the big difference between the const and non-const global):