Gilad Naor
Gilad Naor

Reputation: 21556

What happens when passing reference to literal in 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...

Upvotes: 7

Views: 2242

Answers (2)

Eugene Yokota
Eugene Yokota

Reputation: 95654

  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;
}

Upvotes: 1

sharptooth
sharptooth

Reputation: 170509

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.

Upvotes: 6

Related Questions