[英]GCC -Wconversion warning for 16-bit addition
What would be the proper way to resolve warnings of this kind in the existing codebase? 解决现有代码库中此类警告的正确方法是什么?
void test(uint16_t x, uint16_t y)
{
// warning: conversion to 'uint16_t' from 'int' may alter its value
uint16_t value = (x + 1) * y;
...
}
All three values are unsigned 16-bit integers and any arithmetical overflows would be performed correctly without warnings it this platform's int
was 16-bit, and I don't see another way this piece of code should be written, apart from casting the result due to integer promotion. 所有这三个值都是无符号的16位整数,任何算术溢出都将正确执行,而不会警告该平台的
int
是16位,而且除了强制转换结果外,我看不到应该编写这段代码的其他方式整数促销。
Should I cast in all such cases?
我应该在所有这些情况下投身吗? Casting feels like I am doing something wrong.
投放感觉就像我做错了什么。
It's the correct thing to do here, at least if the code should be portable. 至少在代码应该可移植的情况下,这才是正确的做法。 If it's only ever compiled for 16bit platforms, there shouldn't be a warning, otherwise, silence the warning with an explicit cast to
uint16_t
: 如果仅针对16位平台进行编译,则不应发出警告,否则,请使用明确的
uint16_t
为uint16_t
来使警告静音:
uint16_t value = (uint16_t) (x + 1) * y;
There's nothing better you can do: all arithmetic operations are carried out as (at least) int
and the compiler reminds you of it. 没有什么可以做的更好了:所有算术运算都(至少)以
int
,并且编译器会提醒您。 Depending on the values of x
and y
, it's quite possible the result doesn't fit in an uint16_t
. 根据
x
和y
的值,结果很可能不适合uint16_t
。 Explicitly writing the cast documents you're aware of that and either want the truncation or assure it won't happen. 明确地编写您知道的演员表文件,或者想要截断或确保不会发生截断。
Note: the following is only true in the 16-bit int case 注意:以下仅适用于16位int情况
warning: was about implicit conversion of x
to int
because 1
is of type int
. 警告:关于
x
到int
隐式转换,因为1
的类型为int
。 Later conversion of y
to int
for same reason would also trigger this. 出于相同原因,以后将
y
转换为int
也会触发此操作。
Simply mark the 1
as unsigned 只需将
1
标记为未签名
void test(uint16_t x, uint16_t y)
{
uint16_t value = (x + 1u) * y;
...
}
No casting required. 无需铸造。
This will also work in 16 bit case : 这也将在16位的情况下工作 :
void test(uint16_t x, uint16_t y)
{
uint16_t value = x * y + y;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.