Bitwise-or operator used on a sign-extended operand in Visual Studio 2015

那年仲夏 提交于 2019-11-29 01:41:26

This is just a bug. The code to detect and report this error was added very late in the VS2015 development (see https://github.com/dotnet/roslyn/issues/909 and https://github.com/dotnet/roslyn/pull/2416) and it detects too many cases compared to VS2013. There is now a bug report (https://github.com/dotnet/roslyn/issues/4027) to repair this.

Sign extension is happening, but possibly not for the obvious reason, and not in a worrying way, IMO.

This code:

a |= (short) b;

is equivalent to:

// No warning here... (surprisingly, given that `a` is being sign-extended...)
a = (short) (a | (short) b);

Which is equivalent to:

// No warning here...
a = (short) ((int) a | (int) (short) b;

because the | operator isn't defined for short operands anyway. Both operands are promoted to int, then the result is cast back to short.

It's not clear why the compiler decides to warn in this case, but there is sign extension occurring... albeit in a harmless way.

Note that you get the same warning if no int variables are involved at all:

short a = 10;
short b = 20;
a |= b; // CS0675

Given the way that the | operator works with casts, this looks entirely harmless to me. I'm not sure whether I'd call it a compiler bug, but it definitely looks like non-ideal behaviour to me. Will ping C# compiler team members to see what I've missed :)

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