If compiler can perform implicit narrowing conversion on an integer literal, then it should also
If compiler is able to implicitly convert integer literal into byte type and assign the result to b ( b = 100; ), why can’t it also implicitly assign the result of an expression a+100 ( result is of type int开发者_StackOverflow社区eger ) to b?
byte a = 10;
byte b = a; //ok
b = 100; //ok
b = a + 100;//error - explicit cast needed
b = (byte)(a + 100); // ok
thanx
It's all about static type safety - whether, at compile time, we can safety know the type of an expression. With a literal, the compiler can correctly tell that if it can be converted to a byte. In byte a = 20
, 20 is convertible, so it all goes through fine. byte a = 257
won't work (257 can't be converted).
In the case byte b = a
, then we already know a is a byte, so type safety is assured. b = 100
is again fine (it's statically known that 100 is convertible).
In b = a + 100
, it is not statically known if a + 100
is a byte. a
could contain 200, so a + 100
is not representable as a byte. Hence the compiler forces you to tell it "Yes, a + 100
is always a byte" via a cast, by appealing to your higher level programmer knowledge.
Some types of more advanced type systems don't suffer from this problem, but come with their own problems that most programmers won't like.
The compiler allows you to implicitly convert an integer literal into a byte, since it can, at compile time, check the value of the literal to make sure that it's a byte, and treat it as a byte literal.
You can see this if you try the following:
byte a = 10; // Works, since 10 is valid as byte
byte b = 239832; // Gives error!
The error you get if you put an arbitrary int is:
Error 1 Constant value '239832' cannot be converted to a 'byte'
When you're adding a literal to a byte:
b = a + 100
There's the potential for overflowing, so it's not implicitly allowed. You need to tell the compiler that you explicitly want this to happen, via a cast.
If you use the assigning version of the operator (+=
) then it will perform the narrowing conversion on the result without reporting an error:
byte a = 10;
byte b = a; //ok
b = 100; //ok
b = a;
b += 100;//ok
Because treating literals specially is easy and useful; having the compiler distinguish all expressions consisting of compile-time constants and treat them specially would be far more work and far less useful.
精彩评论