使用运算符<< = on unsigned char时发生Wconversion警告 [英] -Wconversion warning while using operator <<= on unsigned char
问题描述
当我用gcc编译下面的代码时:
int main()
{
unsigned char c = 1;
c<< = 1; //警告在这行
返回0;
}
我得到这个警告:
从'int'转换为'unsigned char'可能会改变它的值[-Wconversion]
为什么这段代码有什么问题?其实,我真的可以在 unsigned char
变量上使用操作符< =
吗?
汇编命令: b
code> g ++ test.cpp -Wconversion -o test.exe
c <= lt; = 1;
相当于:
c = c<< 1
以及<<
说操作数被提升,并且在这种情况下将被提升为 int
,结果是升级类型。因此,在最后会有一个从 int
到 unsigned char
的转换,这可能会导致改变的值。 p>
代码是有效的,警告告诉您隐式转换正在发生,并且在某些情况下,转换可能会改变该值。使用演员将会使警告消失。隐式转换的结果可能非常不直观,并且在某些情况下未定义的行为。有关详细信息,请参阅 gcc Wconversion wiki 。
如果没有手动扩展操作并使用 static_cast
:
c = static_cast< unsigned char>(c<< 1);
正如我们从这个 gcc bug report 并非所有人都认为这是一个有用的警告。
有关草稿C ++标准部分 5.8
移位操作符:
操作数应为积分或非范围的枚举类型和积分促销被执行。结果的类型是升级的左操作数[...]
以及
表达式E1 op = E2的表达式的行为等同于E1 = E1 op E2除了E1是
只评估一次。 [...]
When I compile the following code with gcc :
int main()
{
unsigned char c = 1;
c <<= 1; // WARNING ON THIS LINE
return 0;
}
I get this warning :
conversion to ‘unsigned char’ from ‘int’ may alter its value [-Wconversion]
Why ? What is wrong with this code ? Actually, can I really use the oprator <<=
on a unsigned char
variable ?
Compilation command :
g++ test.cpp -Wconversion -o test.exe
This is a valid warning:
c <<= 1;
is equivalent to:
c = c << 1
and the rules for <<
say that the operands are promoted and in this case will be promoted to int
and the result is of the promoted type. So there will be a conversion from int
to unsigned char
at the end which may result in an altered value.
The code is valid, the warning is telling you that an implicit conversion is happening and in some cases the conversion could alter the value. Using a cast will silence the warning. Results of implicit conversions can be very counter-intuitive and in some cases undefined behavior. See the gcc Wconversion wiki for some details.
I don't see a way to remove the warning without expanding the operation out manually and using static_cast
:
c = static_cast<unsigned char>( c << 1 );
As we can see from the long thread on this gcc bug report not everyone feels that this is a useful case for this warning.
For reference from the draft C++ standard section 5.8
Shift operators:
The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand [...]
and from section 5.17
Assignment and compound assignment operators:
The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. [...]
这篇关于使用运算符<< = on unsigned char时发生Wconversion警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!