The compiler does narrow the byte b = 3; as it is doing in line 1. However the last line of your code appears to be the real problem here because you are trying to add to bytes which will result in an int so you cannot assign it to byte type variable. Looking at your code, it seems you might get a compile error in line 2 because you define variable b which has already been defined in line 1.
byte b = 3; byte c = 8; byte d = b + c; //compile error !
because result of an expression involving int sized or smaller is always int. So if you add two byte result is int. if you divide short by int result is int and so on.
the problem here is that for the compiler it makes a difference if you assign an integer literal like "3" or if you assign an expression like "b + c". For you it may be obvious that "b + c" in this could be stored into a byte variable without loss of information but for the compiler the value of such an expression isn't known at compile time so it has to assume that the expression "b + c" could lead to an overflow if you try to put it in a byte variable. Therefore you have to explicitly cast it to a byte telling the compiler that you know there could be loss of precision and that's OK for you
Maybe I didn't get the point, Jack. Anyway, Pawni Jain is right. In addition I can add that when declaring a variable like byte b = 3 (or - in case of byte type - with any other value <= 127) the compiler is smart enough to notice that this number will fit into 8-bit byte so it narrows this - otherwise int literal - implicitely to byte.
For you it may be obvious that "b + c" in this could be stored into a byte variable without loss of information but for the compiler the value of such an expression isn't known at compile time .
and i think this is the point.
Post by:autobot
There’s no place like 127.0.0.1. But I'll always remember this tiny ad:
a bit of art, as a gift, the permaculture playing cards