. Advertisement .
..3..
. Advertisement .
..4..
I am tired of fixing the problem: initial value of reference to non-const must be an lvalue in the cpp; even if I get the reference from another forum, it still returns an error:
Error : initial value of reference to non-const must be an lvalue
To identify the problem, I will show you the detail here:
#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();
}
How do I do that? Could you support me in improving this problem?
The cause: You are informing the compiler that you intend to change the value of a pointer when you send it by a non-
const
reference. The compiler believes that even if your code does not currently accomplish that, it will do it. That is why the error: initial value of reference to non-const must be an lvalue occurs.Solution:
Declare
x
a constant to correct this issue:Another way, prior to running
test
, create a variable to which you attach a pointer tonKByte
:The
&nKByte
creates an unconstrained temporary value that cannot be bound to any non-const.You can change
void test(float *&x)
intovoid test(float * const &x)
, or drop the pointer entirely and usevoid test(float &x); /*...*/ test(nKByte);
.