assigning char to int reference and const int reference in C++
c++, c++03, casting, constants, reference
Solution
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.
Problem
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.