Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass int by const reference or by value , any difference? [duplicate]

When I pass primitives like int and double to functions , is it better to pass them by const reference , or by value (assuming that I don't change the variable's value) ?

int getValueFromArray(int index)
{
    // return the value from the array
}


int getValueFromArray(const int& index)
{
    // return the value from the array
}

Thanks

like image 670
JAN Avatar asked May 18 '15 02:05

JAN


People also ask

Is it better to pass by reference or value?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

What is the difference between pass by reference and pass by const reference?

From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified.

Does const reference make a copy?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .

Is pass by reference faster than pass by value?

As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer. .


1 Answers

For primitive types, passing by value is much better than passing by reference. Not only is there no indirection, but with a reference, the compiler has to worry about potential aliasing, which can ruin optimization opportunities.

Finally, pass-by-reference causes lvalues to become odr-used, which can actually cause linker errors. And this final issue doesn't go away if the call gets inlined.

like image 102
Ben Voigt Avatar answered Oct 10 '22 17:10

Ben Voigt