68

I'm trying to send value into function using reference pointer but it gave me a completely non-obvious error

#include "stdafx.h"
#include <iostream>

using namespace std;

void test(float *&x){
    
    *x = 1000;
}

int main(){
    float nKByte = 100.0;
    test(&nKByte);
    cout << nKByte << " megabytes" << endl;
    cin.get();
}

Error : initial value of reference to non-const must be an lvalue

I have no idea what I must do to repair above code, can someone give me some ideas on how to fix that code?

cigien
  • 57,834
  • 11
  • 73
  • 112
Mohd Shahril
  • 2,257
  • 5
  • 25
  • 30

5 Answers5

73

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
Rachit Agrawal
  • 3,203
  • 10
  • 32
  • 56
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • your example with explanation is awesome, so i understand it now `temporary value`, also, your solution `float *nKBytePtr = &nKByte;` also different with another answers, so i have(must!) choose your solution as an answers.. thanks again :D – Mohd Shahril Jul 21 '13 at 10:51
14

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

wilx
  • 17,697
  • 6
  • 59
  • 114
9

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Simply replace test(&nKByte); with test(nKByte); in main function

0

Simply, initializers of references are expected to be objects not their addresses, but if you need to assign a reference to otherwise (like your code above), declare this reference as const. Why const? because if not, the compiler does think that you need to, later on, modify the pointer itself not what it's pointing to.

mada
  • 1,646
  • 1
  • 15