在比较UINT16_T和UNSIGNED INT时,为什么存在签名问题?
我有这样的代码:
#include <iostream>
using std::cout;
using std::endl;
int main() {
uint16_t a = 0;
uint16_t b = 0;
if ( a - b < 3u )
{
cout << "cacahuète" << endl;
}
return 0;
}
当我使用-wall
对G ++进行编译时,我会得到:
temp.cpp: In function ‘int main()’:
temp.cpp:9:13: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]
9 | if ( a - b < 3u )
| ~~~~~~^~~~
如果我编写,则不会显示该警告,如果(a -b&lt; static_cast&static_cast&lt; uint16_t&gt ;(3U))
而不是。
- 那是怎么回事? INT来自哪里?
- 这实际上会导致不正确的行为吗?
- 是否有较少的详细方法来使它保持沉默? (还是写uint16_t字面的详细方法?)
I have a code like this :
#include <iostream>
using std::cout;
using std::endl;
int main() {
uint16_t a = 0;
uint16_t b = 0;
if ( a - b < 3u )
{
cout << "cacahuète" << endl;
}
return 0;
}
When I compile it using g++ with -Wall
, I get :
temp.cpp: In function ‘int main()’:
temp.cpp:9:13: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]
9 | if ( a - b < 3u )
| ~~~~~~^~~~
That warning doesn't show up if I write if ( a - b < static_cast<uint16_t>(3u) )
instead.
- So what's going on, here ? Where does the int come from?
- Can this actually result in an incorrect behavior?
- Is there a less verbose way to silence it? (or a less verbose way to write a uint16_t literal?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
整数促销正在这里进行。在
std :: uint16_t
的系统上,它小于int
,将其升级为int
(大多数二进制操作)时。在
a -b
中,两个操作数均升级为int
,结果是int
。您将此签名的整数与3U
进行比较,该整数是insted int
。迹象有所不同,因为编译器警告您。在这里,右手操作数也被提升为
int
。比较的两面都签署了,因此没有警告。如果(a -b&lt; static_cast&lt; uint16_t&gt;(3U))
的行为确实不同于a -b&lt; static_cast&lt; uint16_t&gt;(3U)
。如果一个是正确的,那么大概另一个是不正确的。正确的解决方案取决于您想要正确的行为。
ps您忘了包含定义
uint16_t
的标题。Integer promotion is going on here. On systems where
std::uint16_t
is smaller thanint
, it will be promoted toint
when used as an operand (of most binary operations).In
a - b
both operands are promoted toint
and the result isint
also. You compare this signed integer to3u
which isunsigned int
. The signs differ, as the compiler warns you.Here, the right hand operand is also promoted to
int
. Both sides of comparison are signed so there is no warning.if ( a - b < static_cast<uint16_t>(3u) )
does have different behaviour thana - b < static_cast<uint16_t>(3u)
. If one is correct, then presumably the other is incorrect.The correct solution depends on what behaviour you want to be correct.
P.S. You forgot to include the header that defines
uint16_t
.