Page 1 of 1

numeric promotion

Posted: Thu Sep 09, 2021 7:44 am
by nick12345
Hello,

I have a question about this code example:

Why do we have a compiler time error?
Casting comes befor + operator, so I dont' understand why do we have int now.

Code: Select all

	short a = 1;
	short b = 2;
	short c = (short)a + (short)b;
I know, correct will be

Code: Select all

int c = a + b;
or

Code: Select all

short c = (short) ( a+b )
due to numeric promotion;

Re: numeric promotion

Posted: Thu Sep 09, 2021 10:38 pm
by admin
Good question. That is because a result of a binary numeric operation is always at least as large as an int. So, even though you have cast a and b to short, the result of the plus operator is still an int, which can't be assigned to a short without a cast. This is explained in detail in JFC JA Fundamentals study guide by Hanumant Deshmukh on page 123.
test.png
test.png (79.51 KiB) Viewed 5276 times

Re: numeric promotion

Posted: Wed Sep 15, 2021 10:35 am
by hakim homsy
Thanks