Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what scenarios would you declare a non-reference, non-pointer type function parameter const?

Tags:

c++

I have the following function declaration:

void fn(int);

This function has a single integral type parameter. Now, I could call this function by passing a non const or a const integral object. In either case, this function is going to copy the object to its local int parameter. Therefore, any modifications to this parameter is going to be local to the function and is not going to affect the actual arguments of the caller in any way. Now my question is under which scenario will I declare this single int parameter to be of const type? I don't see a need to declare this function as follows.

void fn(const int);

This is because the arguments are going to be anyway passed by value and the function can in no way modify the arguments in either case. I understand that by declaring a parameter constant the function cannot modify it inside its body. However, there is no downside here even if the function modifies since the parameter is local to the function.

like image 649
naivnomore Avatar asked Sep 17 '25 23:09

naivnomore


2 Answers

You're right that to the caller there is no difference -- it only matters inside the function. I prefer to add the const whenever I can. As I'm writing the function, I'm thinking "I want this parameter but have no intention of modifying it (even just locally)" and the compiler will keep me honest.

Also, in some cases the compiler may be able to do more optimizations if it knows the variable is const (as in loop bounds).

like image 100
Pat Notz Avatar answered Sep 20 '25 14:09

Pat Notz


Just because it's allowed, doesn't mean there's a point to it.

I wouldn't be surprised if this could cause overloading to behave slightly differently, but I think you're basically right - there's no good outside-the-function reason to do it.

One possible problem is confusing readers who might think you intended a reference instead, but forgot the "&".