Stupid compiler error

  • Thread starter Thread starter rollasoc
  • Start date Start date
R

rollasoc

Hi,

Made me laugh so I though I'd share this.

short i = 32;
short j = 1;
short k = i + j;

gives an error
Cannot implicitly convert type 'int' to 'short'

That is a bit poo in my reckoning...

at least the following compiles.

short k = (short)(i + j);
 
Hello, rollasoc!

r> short i = 32;
r> short j = 1;
r> short k = i + j;

int k = i + j; // Ok
 
The same thing happens in Java, and there it seems that '+' will return
"at least int, because of normal promotions".
 
Hello

The CLR can perform arithmetic operations on 32 bit or 64 bit values only.
It can't perform 16 bit or 8 bit operations.
So the i and j are implicitly converted to Int32, then added, so the result
of the addition is an Int32, which have to be explicitly cast to short to
get a short result.

Best regards,
Sherif
 
Hi,

That's the normal behavior, see this scenario
short i = 32767 ; // the max positive value of a short aka int16
short j = 32;

the result of i + j overflow a short, so basically you have three choises:
1- ignore the overflow and do nothing, now you have an invalid result in k ,
tracking this error is a big pain!! ( I don;t really remember but I think
that this is what C/C++ does )

2- have the compiler do the check and throw an Overflow Exception, very
costly as now a lot of operations must be checked for this. C# provided a
controled way of doing this, see the checked keyword in C#

3- Automatically promote the type , this is the safer and faster way . I
think that Jave does this too ( is that right jon? )



Hope this help,
 
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us> said:
That's the normal behavior, see this scenario
short i = 32767 ; // the max positive value of a short aka int16
short j = 32;

the result of i + j overflow a short, so basically you have three choises:
1- ignore the overflow and do nothing, now you have an invalid result in k ,
tracking this error is a big pain!! ( I don;t really remember but I think
that this is what C/C++ does )

2- have the compiler do the check and throw an Overflow Exception, very
costly as now a lot of operations must be checked for this. C# provided a
controled way of doing this, see the checked keyword in C#

3- Automatically promote the type , this is the safer and faster way . I
think that Jave does this too ( is that right jon? )

Yup, Java does the same thing. Of course, the result of adding two ints
could overflow too - I believe it's more for efficiency reasons than to
avoid overflow, if you see what I mean. Modern processors tend to have
instructions to add 2 32-bit integers, but possibly not 16 or 8 bits...
 
Back
Top