10

I noticed that assigning a char to a const int& compiles, but assigning it to a int& gives a compilation error.

char c;
int& x = c;    // this fails to compile
const int& y = c;    // this is ok

I understand that it is not a good practice to do this, but I am curious to know the reason why it happens.

I have searched for an answer by looking for "assigning to reference of different type", "assigning char to a int reference", and "difference between const reference and non-const reference", and came across a number of useful posts (int vs const int& , Weird behaviour when assigning a char to a int variable , Convert char to int in C and C++ , Difference between reference and const reference as function parameter?), but they do not seem to be addressing my question.

My apologies if this has been already answered before.

Community
  • 1
  • 1
Masked Man
  • 1
  • 7
  • 40
  • 80
  • @downvoter would you mind explaining the reason? I want to learn how I can improve the quality of my questions here, since I plan to visit this site regularly. :) – Masked Man Dec 08 '12 at 18:57

3 Answers3

8
int& x = c;

Here an implicit conversion from char to int is being performed by the compiler. The resulting temporary int can only be bound to a const reference. Binding to a const int& will also extend the lifetime of the temporary result to match that of the reference it is bound to.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
3

This behaviour is justified in the standard N4527 at 8.5.3/p5.2 References [dcl.init.ref]

5 A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

...

5.2 Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference. [ Example:

double& rd2 = 2.0; // error: not an lvalue and reference not const
int i = 2;
double& rd3 = i; // error: type mismatch and reference not const

— end example ]

101010
  • 41,839
  • 11
  • 94
  • 168
1

The fact that the line

const int& y = c; 

creates a temporary and y binds to the temporary can be verified by the following:

#include <iostream>

int main()
{
   char c = 10;
   const int& y = c;

   std::cout << (int)c << std::endl;
   std::cout << y << std::endl;

   c = 20;

   std::cout << (int)c << std::endl;
   std::cout << y << std::endl;

   return 0;
}

Output:

10
10
20
10

The value of y did not change when the value of c was changed.

R Sahu
  • 204,454
  • 14
  • 159
  • 270