I know for a function this simple it will be inlined:
int foo(int a, int b){
return a + b;
}
But my question is, can't the compiler just auto-detect that this is the same as:
int foo(const int a, const int b){
return a + b;
}
And since that could be detected, why would I need to type const
anywhere? I know that the inline
keyword has become obsolete because of compiler advances. Isn't it time that const
do the same?
When you declare a const in your program, int const x = 2; Compiler can optimize away this const by not providing storage for this variable; instead it can be added to the symbol table. So a subsequent read just needs indirection into the symbol table rather than instructions to fetch value from memory.
Constant expressions. Certain forms of expressions, called constant expressions, can be evaluated at compile time. In const contexts, these are the only allowed expressions, and are always evaluated at compile time.
const variables are variables that a function (or structure) promises not to change, though other things may change that same variable.
Difference between Run-time and Compile-time constants 1. A compile-time constant is a value that is computed at the compilation-time. Whereas, A runtime constant is a value that is computed only at the time when the program is running. 2.
You don't put const
as the result of not modifying a variable. You use const
to enforce you not modifying it. Without const
, you are allowed to modify the value. With const
, the compiler will complain.
It's a matter of semantics. If the value should not be mutable, then use const
, and the compiler will enforce that intention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With