Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting Int16's only works with literals

When I write this code in VS, it doesn't work ("Cannot implicitly convert 'int' to 'short'. An explicit conversion exists. Are you missing a cast?"):

short A = 5;
short B = 1 << A;

Yet this code is absolutely fine:

short A = 1 << 5;

I know I can make the error go away by casting the entire expression as a short, but can anyone tell me why this happens?

like image 924
Tharwen Avatar asked Oct 19 '12 23:10

Tharwen


2 Answers

Because A is not a literal, the compiler doesn't know that the result is representable as a short. Therefore it needs an explicit cast. With the literal 5, the compiler sees that the result is 32, which can fit in a short.

like image 74
Daniel Fischer Avatar answered Nov 16 '22 08:11

Daniel Fischer


The C# Language specification 4.0 states in 6.1.9:

A constant-expression (§7.18) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

Conversion of constant expressions is one of the special cases where this will be implicit (6.1).

like image 2
MrDosu Avatar answered Nov 16 '22 09:11

MrDosu