Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

integers initialization - Interesting !!!!

 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I thinks this comment is quite interesting.
This is a basic initialization, which of course compiles.


Naturally, as you know, the following code doesn't compile.
Block 1:

You can note that I exceeded by one unity the limits for the given data types.

The following is more interesting. It doesn't compile for the first 3 cases, but it compiles for the last one.
Block 2:


It'd have been very easy to guess that the fourth option wouldn't compile, but it actually does.
The point is that in Block 1 initializations the compile error for the first 3 is a casting error (cannot convert from int to short, char, etc...). But the compile error for the last case in Block 1 is an out of range error.

Then I guess that in block 2, the compiler is not smart enoght to realize that it adding one to the int limit will became out of range, am I right???
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Leandro Melo:



In the above expression, the you have a literal constant of 2147483648 which is outside the limit.

Below however, you have an expression which when evaluated will result to -2147483648, which is still within the limit of an integer type.
 
Adam Czysciak
Ranch Hand
Posts: 90
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Leandro Melo:

The following is more interesting. It doesn't compile for the first 3 cases, but it compiles for the last one.
Block 2:


It'd have been very easy to guess that the fourth option wouldn't compile, but it actually does.
The point is that in Block 1 initializations the compile error for the first 3 is a casting error (cannot convert from int to short, char, etc...). But the compile error for the last case in Block 1 is an out of range error.

Then I guess that in block 2, the compiler is not smart enoght to realize that it adding one to the int limit will became out of range, am I right???


Well, the only explanation I see is compiler doesn't perform value checking, only type checking. The result of + operator on numbers is always typed at least int, therefore first 3 lines cannot compile without the casts. Fourth line is typed int, so it compiles. Of course the 'smart' compiler could check the value (I'm not sure what JLS says about it), but what in case of some other compiler that does not do it?
 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Alton has clarified this.
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic