Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'const' for function parameters

Tags:

c++

constants

How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:

void SetValue(const bool b) { my_val_ = b; } 

Is that const actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?

I was also surprised to learn that you can omit const from parameters in a function declaration but can include it in the function definition, e.g.:

.h file

void func(int n, long l); 

.cpp file

void func(const int n, const long l) 

Is there a reason for this? It seems a little unusual to me.

like image 334
Rob Avatar asked Sep 22 '08 20:09

Rob


People also ask

Why do we use const in functions?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.

What does const in function parameter mean C++?

C++ solution: constant parameters. When you put "const" in front of a parameter, it means that it cannot be modified in the function. (In other words, you'll get a compile-time error if you try to assign to it.)

What is a const parameter?

A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.

What effect does the const keyword have on a function parameter?

Declaring function parameters const indicates that the function promises not to change these values. In C, function arguments are passed by value rather than by reference. Although a function may change the values passed in, these changed values are discarded once the function returns.


1 Answers

const is pointless when the argument is passed by value since you will not be modifying the caller's object.

Wrong.

It's about self-documenting your code and your assumptions.

If your code has many people working on it and your functions are non-trivial then you should mark const any and everything that you can. When writing industrial-strength code, you should always assume that your coworkers are psychopaths trying to get you any way they can (especially since it's often yourself in the future).

Besides, as somebody mentioned earlier, it might help the compiler optimize things a bit (though it's a long shot).

like image 109
rlerallut Avatar answered Sep 28 '22 12:09

rlerallut