Thursday, January 25, 2018

compiler errors - Why does the Java increment operator allow narrowing operations without explicit cast?











In Java, this is not valid (doesn't compile), as expected:



long lng = 0xffffffffffffL;
int i;

i = 5 + lng; //"error: possible loss of magnitude"


But this is perfectly fine (?!)



long lng = 0xffffffffffffL;
int i = 5;
i += lng; //compiles just fine



This is obviously a narrowing operation, that can possibly exceed the int range. So why doesn't the compiler complain?


Answer



i += lng; compound assignment operator cast's implicitly.



i+=lng; 
is same as
i = int(i+lng);


FROM JLS:





A compound assignment expression of the form E1 op= E2 is equivalent
to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1
is evaluated only once.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...