Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char array compile time error upon assign a value from array

Tags:

java

arrays

char

So I have this code

char [] a = {'a','b','c'};

char c = 'a' + 'b'; //works
char c2 = 98 + 97; //works
char c3 = a[0] + a[1]; //compile time error

So all of them are the same functionality but upon getting and using an array value it is giving me a compile time error. What is the cause of this??

The result of the additive operator applied two char operands is an int.

then why can I do this?

char c2 = (int)((int)98 + (int)97);
like image 346
game on Avatar asked Aug 08 '14 05:08

game on


1 Answers

The result of the additive operator applied two char operands is an int.

Binary numeric promotion is performed on the operands. The type of an additive expression on numeric operands is the promoted type of its operands

The first two are constant expressions where the resulting value is an int that can be safely assigned to a char.

The third is not a constant expression and so no guarantees can be made by the compiler.

Similarly

then why can I do this?

char c2 = (int)((int)98 + (int)97);

That is also a constant expression and the result can fit in a char.

Try it with bigger values, 12345 and 55555.

like image 129
Sotirios Delimanolis Avatar answered Oct 25 '22 15:10

Sotirios Delimanolis