![](/img/trans.png)
[英]Teensy LidarLite LIDAREnhanced no known conversion for argument 2 from 'int16_t* {aka short int*}' to 'int*'
[英]Narrowing conversion of ‘(((int)a) + -1)’ from ‘int’ to ‘int16_t {aka short int}’ inside { }
我有以下“ test.cpp”文件:
#include <cstdint>
struct Struct
{
int16_t val;
};
int main()
{
int16_t a = 0;
//Struct b = {.val = a}; // No warning
Struct b = {.val = a-1}; // Warning
(void)b;
return 0;
}
当使用'g ++ -std = c ++ 11 -o test test.cpp'进行编译时,出现以下警告:
test.cpp: In function ‘int main()’:
test.cpp:12:29: warning: narrowing conversion of ‘(((int)a) + -1)’ from ‘int’ to ‘int16_t {aka short int}’ inside { } [-Wnarrowing]
Struct b = {.val = a-1};
^
有办法摆脱它吗?
减去1时, a
的类型提升为int
。您可以通过对整个表达式执行static_cast
解决该问题:
Struct b = { .val = static_cast<int16_t>(a - 1) };
请注意,如果使用普通的int
类型完成某些平台(例如x86)的算术运算,可能会更快。
Struct b = {.val = (int16_t)(a-1)}; // cast as expected, by default formula produces int
请注意,如果我使用-pedantic进行编译:
pi@raspberrypi:/tmp $ g++ -pedantic c.cc
c.cc: In function ‘int main()’:
c.cc:12:20: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
Struct b = {.val = (int16_t)(a-1)}; // Warning
最好有
Struct b = {(int16_t)(a-1)}; // no warning even with -pedantic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.