Answer to Question #24382 in C++ for Nourah

Question #24382
Why is constant call-by-reference often the best way to pass a struct-type value to a function?
Expert's answer
Pass by const reference

One of the major disadvantages of pass by value is that all arguments passed by value are copied to the parameters. When the arguments are large structures or classes, this can take a lot of time. References provide a way to avoid this penalty. When an argument is passed by reference, a reference is created to the actual argument (which takes minimal time) and no copying of values takes place. This allows us to pass large structures and classes with a minimum performance penalty.

However, this also opens us up to potential trouble. References allow the function to change the value of the argument, which in many cases is undesirable. If we know that a function should not change the value of an argument, but don’t want to pass by value, the best solution is to pass by const reference.

You already know that a const reference is a reference that does not allow the variable being referenced to be changed. Consequently, if we use a const reference as a parameter, we guarantee to the caller that the function will not (and can not) change the argument!

The following function will produce a compiler error:

void foo(const int &x)
x = 6;& // x is a const reference and can not be changed!
Using const is useful for several reasons:

It enlists the compilers help in ensuring values that shouldn’t be changed aren’t changed.
It tells the coder whether they need to worry about the function changing the value of the argument
It helps the coder debug incorrect values by telling the coder whether the function might be at fault or not
Rule: Always pass by const reference unless you need to change the value of the argument

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

New on Blog