Literals and implicit narrowing conversions

怎甘沉沦 提交于 2020-01-04 17:51:50

问题


a) Shouldn’t the following assignment cause an error, since number 100 is a literal of type int and since compiler doesn’t allow implicit narrowing conversions?

byte b = 100; 


b) If compiler doesn’t complain about implicit narrowing conversion from int literal to type byte, then why doesn’t it also allow an implicit narrowing conversion from double literal to type float ( I realize we could avoid this error by specifying float literal using F/f suffix )?

byte b=16; //OK
float f1=16.9; //error


thank you


回答1:


This is covered in section 6.1.8 of the C# language spec. It is legal for constant expressions of type int to be converted to sbyte, byte, short, ushort, uint or ulong provided the value is within the range of the target type. It is fairly easy for the C# compiler to determine if the value is within the appropriate range and hence allow the conversion.

As for the double case, the C# lang spec does not specifically call out why this is not allowed. My guess is it has to do with difficulties in determining if the double value can fit within the float value. Getting floating point precision correct is a very difficult task and probably so much so it wasn't deemed to be worth the cost (if it was possible at all)



来源:https://stackoverflow.com/questions/2217894/literals-and-implicit-narrowing-conversions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!