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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With