• Post Reply Bookmark Topic Watch Topic
  • New Topic

int -> byte , short , char  RSS feed

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte b = 23 ;

a literal ( should not be fraction ) is always int by default . But compiler automatically cast if the literal is in limit of byte . So above statement is perfect .

byte b1 = 4;
byte b2 = 6;
byte add = b1+b2;

why it doesn't work . the result will come 10 ( it is int .. i am agree ) & it is in limit of byte , do why not compiler automatically cast in this case .

help needed .
thanks .
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler doesn't cast it automatically, because b1 & b2 are variables, meaning they can vary at some time. So, the compiler is bothered. It is worried that problems might occur if the values of b1 and/or b2 changes at runtime, such that the sum of them will exceed the limits of byte.

If you can convince the compiler that the values of b1 & b2 will never change, the compiler will be happy and will keep quite.
You can convince the compiler by saying

[ January 06, 2005: Message edited by: Mani Ram ]
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ultimate explanation .
thank you very much .
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
float f = 2.3;

why in this case compiler doesn't cast double to float implicitly . As 2.3 is in limit of float .

thanks .
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!