有人知道为什么这段代码会产生这样的输出吗? -1 >= 0
!!!
[mahmood@tiger ~]$ cat t.cpp
#include <iostream>
#include <stdint.h>
int main()
{
uint64_t i = 10;
uint64_t j = 10;
int64_t k = -1;
std::cout << "k=" << k << " i-j=" << i-j;
if (k >= i-j)
std::cout << " --> yes k>=i-j\n";
return 0;
}
[mahmood@tiger ~]$ g++ t.cpp
[mahmood@tiger ~]$ ./a.out
k=-1 i-j=0 --> yes k>=i-j
[mahmood@tiger ~]$
我知道类型不同,比较需要两个相似的类型,但最终,它正在比较 -1
和0
。不是吗?
最佳答案
if (k >= i-j)
两边都转换为无符号,所以-1可能被解释为0xFFFFFFFFFFFFFFFF:
if (0xFFFFFFFFFFFFFFFF >= 0)
根据标准(强调我的):
Expressions [expr]
Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.
关于c++ - 比较 int64_t 和 uint64_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735103/