In general, returning a reference avoids that the return value gets copied, and (if it is not const
-qualified) gives you the opportunity to change the “original” value. A return type const T&
is often used in conjunction with objects of class type, e.g. std::vector
, where copying could result in (unwanted) overhead. In conjunction with elementary data types like int
, however, passing back a const int&
is likely to be more overhead than copying the raw int value.
Further, in your example, if you assign the result of type const int&
to a non-reference type, e.g. int largest = max(...)
, the return value is “dereferenced” and assigned by value. So you can change the variable’s content as it is a copy of the const
-referenced value. If you have a type const int&
, and you assign it to a variable of type const int&
, then you get a reference, yet the compiler will not allow you the change it’s contents.
So the only thing where passing back a reference to int
would be without const
, which will then allow you to alter the contents of the “origninal” value.
See the following code; Hope it helps a bit:
int& max(int a[], int length) {
return a[3];
}
const int& maxConst(int a[], int length) {
return a[3];
}
int main(){
int array[] = {12, -54, 0, 123, 63};
int largest = max(array,5);
cout<< "Largest element (value) is " << largest << endl;
largest = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
int largestConst = maxConst(array,5);
cout<< "Largest element (value) is " << largestConst << endl;
largestConst = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
int &largestRef = max(array,5);
cout<< "Largest element (ref) is " << largestRef << endl;
largestRef = 10;
cout << "Element at pos 3 is: " << array[3] << endl;
const int &largestRefConst = maxConst(array,5);
cout<< "Largest element (value) is " << largestRefConst << endl;
// largestRefConst = 10; // -> cannot assign to variable with const-qualified type
//cout << "Element at pos 3 is: " << array[3] << endl;
return 0;
}
Output:
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (ref) is 123
Element at pos 3 is: 10
Largest element (value) is 10
solved What does “const int&” do as a return type?