Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when passing reference to literal in C++?

Tags:

c++

What happens here:

double foo( const double& x ) {
   // do stuff with x
}

foo( 5.0 );
  1. Does the compiler create an anonymous variable and sets its value to 5.0?
  2. Does the x reference a memory location in read-only memory? This is a weird phrasing, I know...

edit: I forgot the const keyword...

like image 377
Gilad Naor Avatar asked Mar 19 '09 07:03

Gilad Naor


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.

Can you pass int by reference?

Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value.

Is passing by reference faster in C?

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.

Can constants be passed by reference?

Passing by const reference is the preferred way to pass around objects as a smart alternative to pass-by-value.


2 Answers

A temporary variable is created for this purpose and it's usually created on stack.

You could try to const_cast, but it's pontless anyway, since you can no longer access a variable once the function returns.

like image 86
sharptooth Avatar answered Sep 22 '22 01:09

sharptooth


  1. What compiler probably does create const literal, but that's not a variable.
  2. A non-const reference cannot point to a literal.

    $ g++ test.cpp test.cpp: In function int main()': test.cpp:10: error: invalid initialization of non-const reference of type 'double&' from a temporary of type 'double' test.cpp:5: error: in passing argument 1 ofdouble foo(double&)'

test.cpp:

#include <iostream>

using namespace std;

double foo(double & x) {
    x = 1;
}

int main () {
    foo(5.0);

    cout << "hello, world" << endl;
    return 0;
}

On the other hand, you could pass a literal to a const reference as follows. test2.cpp:

#include <iostream>

using namespace std;

double foo(const double & x) {
    cout << x << endl;
}

int main () {
    foo(5.0);

    cout << "hello, world" << endl;
    return 0;
}
like image 45
Eugene Yokota Avatar answered Sep 21 '22 01:09

Eugene Yokota