Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const keyword - use liberally?

In the following C++ functions:

void MyFunction(int age, House &purchased_house) {     ... }   void MyFunction(const int age, House &purchased_house) {     ... } 

Which is better?

In both, 'age' is passed by value. I am wondering if the 'const' keyword is necessary: It seems redundant to me, but also helpful (as an extra indication the variable will not be changing).

Does anyone have any opinion as to which (if any) of the above are better?

like image 573
Jessica Avatar asked Oct 12 '09 13:10

Jessica


People also ask

What is the use of const keyword in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

What is the use of the keyword const answer?

What is the const Keyword in C++? We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized.

Is const faster in C?

No, const does not help the compiler make faster code.

Which C keywords are used to declare constants?

const. An identifier can be declared constant by using the const keyword. const int a = 5; To learn more, visit C variables and constants.


1 Answers

First, it's just an implementation detail, and if you put const there, don't put it in the declaration set (header). Only put it in the implementation file:

// header void MyFunction(int age, House &purchased_house);  // .cpp file void MyFunction(const int age, House &purchased_house); {     ... } 

Whether or not a parameter is const in a definition is purely an implementation detail, and should not be part of the interface.

I've not seen this sort of thing often, and i also don't do this. Having the parameter const would confuse me more often than help, because i would immediately pattern-match-fail it to "const int &age" :) The matter of course is entirely different from having const at another level:

// const is a *good* thing here, and should not be removed, // and it is part of the interface void MyFunction(const string &name, House &purchased_house); {     ... } 

In this case, the const will affect whether the function can change the caller's argument. Const in this meaning should be used as often as possible, because it can help ensuring program correctness and improve self-documenting the code.

like image 168
Johannes Schaub - litb Avatar answered Oct 02 '22 16:10

Johannes Schaub - litb