比较 int64_t 和 uint64_t
Comparing int64_t and uint64_t
有人知道为什么这段代码会产生这样的输出吗? -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.
没有。它可能是在比较 0xffffffffffffffff
和 0
。在进行比较之前,signed
变量被提升为 unsigned
类型。在标准中查找 'arithmetic conversions' 了解更多详细信息。
有人知道为什么这段代码会产生这样的输出吗? -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.
没有。它可能是在比较 0xffffffffffffffff
和 0
。在进行比较之前,signed
变量被提升为 unsigned
类型。在标准中查找 'arithmetic conversions' 了解更多详细信息。