G ++ gives an error: incorrect initialization of a link of type 'char & from an expression of type' unsigned char

when i try to compile the following code

int main() { unsigned char uc; char & rc = uc; } 

g ++ gives the following error: invalid initialization of a link of type char & from an expression of type "unsigned char. The same thing happens when using a signed char instead of an unsigned char. But the following compiles fine

 int main() { unsigned char uc; const char & rc = uc; } 

Why can't initialize 'char &' with a variable of type unsigned char ', while you can initialize' const char & 'with it?

+4
source share
3 answers

Why can't initialize 'char &' with a variable of type unsigned char ', while you can initialize' const char & 'with it?

Since the latter creates a temporary reference to the const link, when an unsigned char converted to char , then you cannot do with non-constant links. char , signed char and unsigned char are three different types, as described in C ++ 11 § 3.9.1:

Regular char, signed char and unsigned char are three different types

+5
source

"The C ++ compiler treats variables of type char signed by char and unsigned char as having different types."

The following link will explain: http://msdn.microsoft.com/en-us/library/cc953fe1.aspx

change the following:

 int main() { unsigned char uc; unsigned char& rc = uc; } 
0
source

Today I came across this error and would like to share what I found.

Bjarne Stroustrup in his book "C ++ Programming Language" Third Edition wrote:

§ 5.5 References

Link initialization is trivial when the initializer is an lvalue (an object whose address you can take, see §4.9.6). The initializer for `` plain T & must be an lvalue of type T.

The initializer for const T & does not have to be an lvalue or even a type T In such cases

[1] an implicit type conversion to T is first implied (see §C.6)

[2], then the resulting value is placed in a temporary variable of type T and

[3] finally, this temporary variable is used as the value of the initializer.

0
source

Source: https://habr.com/ru/post/1489546/


All Articles