解决复合赋值转换警告 [英] Resolving a conversion warning in a compound assignment
问题描述
在我的code我有很多的变量<< = 1;
的句子,其中变量
的类型为uint16_t的。编译器随地吐痰警告说
In my code I have a lot of variable <<= 1;
sentences where variable
is of type uint16_t. The compiler is spitting a warning saying
转换从'诠释'uint16_t可能会改变其值[-Wconversion]
conversion to 'uint16_t' from 'int' may alter its value [-Wconversion]
我该如何解决呢?我可以用一个长形的符号,比如变量=(uint16_t)(可变&LT;&LT; 1)
- 但我想保持短期符号。
How can I resolve it? I could use a long-form notation like variable = (uint16_t)(variable << 1)
- but I'd like to keep the short notation.
推荐答案
根据我的标准的阅读,你不能从这个警告这个原因离开:
Based upon my reading of the standard, you can not get away from this warning for this reason:
uint16_t foo;
foo <<= 1;
等同于
uint16_t foo;
foo = foo << 1;
不过,这是在整型提升天下赶上了。
However, this is caught up in the world of "integer promotion".
在富&LT;&LT; 1
的值前pression有类型富
,然而之前可以进行左移它首先必须通过整数推广; C99标准部分的 6.3.1.1.2 规定:如果int可以重新present原始类型的所有值,该值被转换为int
The value of the "foo << 1
" expression has the type of "foo
", however before the left-shift can be conducted it first must go through "integer promotion;" section 6.3.1.1.2 of the C99 standard specifies: "if an int can represent all values of the original type, the value is converted to an int."
这使你的code的非隐版(带额外的括号)如下:
This makes the non-implicit version of your code (with extra parentheses) as follows:
uint16_t foo;
foo = ((int)foo) << 1;
鉴于警告你是32位或64位整数的系统上(或任何比16大,真的)
,你确实推搡一个更大的值到一个较小的一个。
Given the warning you are on a system with either 32 or 64 bit ints (or anything bigger than 16, really), you are indeed shoving a bigger value into a smaller one.
解决此问题的方法是要明确你的演员,像这样:
One way around this is to be explicit with your casts like so:
uint16_t foo;
foo = (uint16_t)(foo << 1);
但是,这意味着,没有,你不能使用较短的按位移位赋值运算符。
But that means that no, you can not use the shorter bitwise shift assignment operator.
如果你真的这样做了一堆,考虑一个辅助功能,使您的code清晰,完全编译。
If you really are doing this a bunch, consider making a helper function that makes your code clear and compiles cleanly.
void LS(uint16_t &value, int shift) { // LS means LeftShift
*value = (uint16_t)(*value << shift);
}
LS(&foo, 1);
TL; DR:不,你不能使用短期操作者,避免在同一时间的警告
TL;DR: No, you can't use the short operator and avoid that warning at the same time.
这篇关于解决复合赋值转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!