If the compiler can perform an implicit narrowing of the conversion in whole literals, then it should also

If the compiler is able to implicitly convert an integer literal to a byte type and assign the result b (b = 100;), why can't it also implicitly assign the result of the expression a + 100 (the result is of type integer) b?

byte a = 10; byte b = a; //ok b = 100; //ok b = a + 100;//error - explicit cast needed b = (byte)(a + 100); // ok 

thanks

+4
source share
4 answers

All about static type security - at compile time we can know the type of expression. With a literal, the compiler can correctly say that if it can be converted to bytes. In byte a = 20 , 20 is convertible, so everything goes through a fine. byte a = 257 will not work (cannot convert 257).

In the case of byte b = a , we already know that a is a byte, so type safety is guaranteed. b = 100 is excellent again (it is statically known that 100 is convertible).

In b = a + 100 not known statically if a + 100 is a byte. a can contain 200, so a + 100 not represented as a byte. Therefore, the compiler forces you to say β€œYes, a + 100 always bytes” through the cast, turning to your higher level knowledge.

Some types of more complex type systems do not suffer from this problem, but come with their own problems that most programmers will not like.

+2
source

The compiler allows you to implicitly convert an integer literal to byte, since during compilation it can check the value of the literal to make sure it is 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:

Error 1 The constant value "239832" cannot be converted to "byte"

When you add a literal to a byte:

 b = a + 100 

There is potential for overflow, so it is implicitly allowed. You need to tell the compiler that you explicitly want this to happen through listing.

+2
source

If you use the assignment version of the operator ( += ), it will narrow the conversion of the result without an error message:

 byte a = 10; byte b = a; //ok b = 100; //ok b = a; b += 100;//ok 
+1
source

Because processing literals is especially simple and useful; the presence of a compiler distinguishes all expressions that consist of compile-time constants and process them specially; it will be much more useful and less useful.

+1
source

Source: https://habr.com/ru/post/1300785/


All Articles