Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the compiler not determine whether a variable is const by Itself?

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?

like image 928
Jonathan Mee Avatar asked Apr 21 '15 11:04

Jonathan Mee


People also ask

What does a compiler do with const?

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.

Is const evaluated at compile time?

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.

Is const considered a variable?

const variables are variables that a function (or structure) promises not to change, though other things may change that same variable.

Is const compile time?

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.


1 Answers

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.

like image 50
tenfour Avatar answered Oct 29 '22 20:10

tenfour