0

Why calling funk(&a) gives a compile error

func(int * & data) {data++;}

int main(){

int a = 5;
int *p = &a;
func(&a); //this gives a compile error
funk(p);  //this works fine 
}

error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’

klido
  • 3
  • 3
  • `funk(p); ` where is this function defined? – roottraveller Jan 25 '16 at 03:53
  • because `a` is of type constant (address can't be changed). you can't change `a` address(which you are doing inside the function). – roottraveller Jan 25 '16 at 03:55
  • 3
    You cannot modify an _rvalue_. That is what `func(&a)` is attempting. When you pass a reference, it must be either an _lvalue_ or have a _const-qualifier_. – paddy Jan 25 '16 at 03:55
  • 1
    @paddy actually rvalues can be modified. Example `std::string().resize(5);` . This code is illegal because it attempts to bind an lvalue reference to an rvalue. – M.M Jan 25 '16 at 05:30

1 Answers1

2

Just as the error message explains, the parameter needs to reference a variable, and &a is not a variable, it's an address of a variable.

Amit
  • 45,440
  • 9
  • 78
  • 110