Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const for non-reference arguments

Tags:

c++

constants

If I have this code:

void Foo(aBasicType aIn) //Where aBasicType is int, char etc.
{
    //...
}

Is there any point in making it const aBasicType since it is going to be copied anyway? One of the reasons I am asking is because I have seen it in 3rd party code and was wondering if there is something I am not aware of.

like image 467
Samaursa Avatar asked May 25 '11 13:05

Samaursa


People also ask

Can we declare a non reference function argument const?

It cannot hurt to declare it const if you know that your function needs not modify its value during execution.

What is a non const reference?

Whether a reference refers to a const or nonconst type affects what we can do with that reference, not whether we can alter the binding of the reference itself." I think this means that making a reference a "const" when it is referenced to a non const object does absolutely nothing.

Can a const reference be bound to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .

What is const argument?

A constant argument is the one whose modification cannot take place by the function. Furthermore, in order to make an argument constant to a function, the use of a keyword const can take place like- int sum (const int a, const int b).


1 Answers

It cannot hurt to declare it const if you know that your function needs not modify its value during execution.

Note that functions that change their arguments, when arguments are passed by value, should be rare.

Declaring your variable const can prevent you from writing if (aIn = someValue).

like image 190
Benoit Avatar answered Nov 08 '22 16:11

Benoit