Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making c++ variables const

I love "const". I wish every variable and method that "ought to be const" IS "const". The problem is that whether a variable or method "ought to be const" depends on methods/variables further down in the call tree. Is there some tool, or some process, for statically examining a body of code and doing "bottom-up en-const-ification"?

like image 225
Mark Lavin Avatar asked May 24 '13 14:05

Mark Lavin


People also ask

How do you define a constant variable?

A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.

Is there const in C?

Yes. const is there in C, from C89.

Can we change const variable in C?

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.

Is const better than #define in C?

In general, const is a better option if we have a choice and it can successfully apply to the code. There are situations when #define cannot be replaced by const. For example, #define can take parameters (See this for example). #define can also be used to replace some text in a program with another text.


1 Answers

I don't know the answer to your question, but I would like to argue against the claim that

whether a variable or method "ought to be const" depends on methods/variables further down in the call tree

Actually, const should be on a logical level. I.e. you should mark something const if it should not be changed logically. If it later is, then you will get a compiler error and will need to reconsider either the fact of changing or your initial assumption.

The rule is:

if something is const, it should not be changed

rather than

if something is not changed de facto, then let's make it const

like image 135
Armen Tsirunyan Avatar answered Sep 20 '22 10:09

Armen Tsirunyan