May assign an integer char value, but may not assign an integer variable to char variable

Why the following code does not compile

int n = 5; char c = n; 

but the following compiles

 char c = 5; 

Don't I assign an integer char value in both cases?

+5
source share
2 answers

A char can be assigned int without translation, because it is an advanced conversion. To do the opposite, an int to char requires a throw because this is a narrowing of the transform.

See also JLS. Chapter 5. Conversions and promotions .

+8
source

His question is why his code does not compile, and not how to do what he is trying to do.

The reason the row

char c = n

does not compile because the range of char (-2 ^ 15 to 2 ^ 15 - 1) is much less than the interval int (-2 ^ 31 to 2 ^ 31 - 1). The compiler sees that you are trying to assign an int to char and stops you because it implements this.

+5
source

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


All Articles