In what scenarios do you declare a non-referenced parameter of a non-pointer function of type const?

I have the following function declaration:

void fn(int);

This function has one integral type. Now I could call this function the transfer of not a const or const-integral object. In any case, this function is going to copy the object into its local int parameter. Therefore, any changes to this parameter will be local to the function and will not affect the actual arguments of the caller. Now my question is, in which scenario will I declare that this single int parameter is of type const? I do not see the need to declare this function as follows.

void fn(const int);

This is due to the fact that the arguments will in any case be passed by value, and this function in no way can change the arguments in any case. I understand that by declaring a parameter constant, a function cannot change it inside its body. However, there are no drawbacks, even if the function changes, since the parameter is local to the function.

+3
source share
5 answers

You are right that there is no difference for the caller - it only matters inside the function. I prefer to add constwhenever I can. When I write this function, I think: “I want this parameter, but I do not intend to change it (even locally)”, and the compiler will keep me informed.

, , , ( ).

+4

. const .

this - const. , . (, this - , , & .) , , const.

+1

, , , .

, , -, , - , .

, , , "&".

+1

++ Spec: http://www.kuzbass.ru:8086/docs/isocpp/over.html

, const / . , const volatile , .

:

typedef const int cInt;

int f (int);
int f (const int);              //  redeclaration of  f(int)
int f (int) { ... }             //  definition of  f(int)
int f (cInt) { ... }            //  error: redefinition of  f(int)
+1

A favorite interview question in a C ++ interview is the difference between passing by values, passing by pointer and passing by reference.

In this case, we pass by value, and this is also int, and therefore it does not matter. But I'm not sure about custom classes. In this case, when the compiler sees that the object is being passed the value of const, he may decide to pass it by reference to const. Nowdays compilers are intelligent, and I do not understand why they cannot do this.

0
source

Source: https://habr.com/ru/post/1763288/


All Articles