Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using const for arguments passed by value? [duplicate]

Say you have:

int f( const T a ) { ... }
int g( const T &a ) { ... }

I understand the use of const in g: we don't know how a is used outside the function, so we want to protect it from being modified. However I don't understand the use of const in f, where a is a local copy. Why do we need to protect it from being modified?

like image 490
usual me Avatar asked Sep 14 '13 00:09

usual me


3 Answers

I can think of a few reasons:

1) When someone reads the code and see const T a, they know that a should not be modified in the body of the function.

2) The compiler will tell you when you try to modify a in the body of the function. Therefore, adding const can prevent mistakes.

BTW chris already mentioned this in the comments.

3) However, there is another difference in C++11. A constant object cannot be moved from, as a move operation modifies the object. Therefore, you can only make a copy of a in the function body and cannot move from it.

4) Also, if this is a class type, you cannot call non-const members functions on a const object.

like image 193
Jesse Good Avatar answered Nov 08 '22 07:11

Jesse Good


Declaring variables const is a good practice.

WHY?

For arguments passed by value to functions, it doesn't matter for the caller whether you declare it const or not. The rationale here is to protect yourself from mistakes while coding, using the compiler to warn you that you are changing the value of a variable, so that you can explicitly confirm this behavior by removing the const modifier. This applies not only to function parameters, but also to local variables.

Based on this rationale, I personaly always start out by declaring all variables const and let the compiler to issue errors when I modify them. Then I check if this behavior is intended and remove the const modifier if it is indeed needed. For better legibility I also always prefer to code in a way my variables are all const.

like image 37
brunocodutra Avatar answered Nov 08 '22 09:11

brunocodutra


"I personally tend to not use const except for reference and pointer parameters. For copied objects it doesn't really matter" If you are using const in function argument there may be one of the following reason. 1-it help the compiler to optimize things a bit. 2-no body can modified argument value in future(if many people working on same code base)

like image 29
saroj kumar Avatar answered Nov 08 '22 07:11

saroj kumar