Home > Mobile >  cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*
cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*

Time:11-08

I am aware that there are some questions similar to this one but I am a beginner in c and those examples were a bit difficult to comprehend for me. In my problem, I have a function called void selectNegatives(int*&,int&,int*&,int&). What this function does is it iterates over an input array, removes negative ints from the input and place them in the output arr. For example an expected output is

input -> -45 11 6 38 -12 0
output -> null
//execute func
input -> 11 6 38 0
output -> -45 -12

My current implementation is as follows. I have removed details of the function because I know the issue is not there.

void selectNegatives(
    int*& inputArr, int& inputSize,
    int*& outputArr, int& outputSize
) {
  //details removed but I can add them if requested
}

My issue is passing int arr[] = {-45, 11, 6, 38, -12, 0}; from caller gives me cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*' while passing int* arr = new int[]{-45, 11, 6, 38, -12, 0}; works. My current understanding is confusing me because isn't arr[] an lvalue?

CodePudding user response:

Case 1

Here we consider the case when int arr[] = {-45, 11, 6, 38, -12, 0};.

Here when passing arr as argument it decays(from int[6] to int*] due type decay but the problem is that this resulting expression is an rvalue(prvalue in particular) and since we can't bind an rvalue to a nonconst lvalue reference we get the mentioned error.

This can also be seen from value category's documentation:

A glvalue may be implicitly converted to a prvalue with lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion.

Case 2

Here we consider the case when int* arr = new int[]{-45, 11, 6, 38, -12, 0};.

In this case, when passing arr as argument the expression arr is an lvalue which is allowed to be bound to a nonconst lvalue reference and so this time it works.

  • Related