1

I am playing a bit around with arrays and passing pointers by reference to functions. Consider as an example the following code:

#include<iostream>

void test_fn(const int* const &i){
    std::cout<<*i<<std::endl;
}

int main(){
    int arr_1[5] {1, 3, 6, 4, 5};
    int *int_ptr1 {nullptr};
    int_ptr1=arr_1;
    test_fn(int_ptr1);

    return 0;
}

This code runs properly.

However, if I amend the definition of the test_fn to read:

void test_fn(const int* &i){
    std::cout<<*i<<std::endl;
}

I get the following error:

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

My question is: Why is this an issue in the second example but not in the first, where the only difference is that the pointer is being passed as a const pointer?

1
  • Why a C-style array and not a std::array?? Commented Jan 29, 2020 at 18:07

1 Answer 1

4

In the 2nd example, the function takes a reference to a non-const const int* pointer, but you are giving it an int* pointer instead. Because the pointer is non-const, the reference cannot be bound to a temporary const int* variable created by the compiler to implicitly convert from int* to const int*. The reference requires a non-const const int* variable at the call site, so you would have to explicitly declare int_ptr1 as const int* instead of int*:

const int *int_ptr1 = arr_1;

In the 1st example, the function takes a reference to a const const int* pointer. Since the pointer is const, the compiler can implicitly convert from int* to const int* and store the result in a temporary variable, and then bind the reference to that temporary.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure which object you are referring to when you say "it cannot be bound to a temporary variable created by the compiler". Is this a hypothetical variable? Edit : Nevermind, the result of the implicit conversion is the rvalue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.