c++ - 比较 int64_t 和 uint64_t

标签 c++ comparison int64 uint64

有人知道为什么这段代码会产生这样的输出吗? -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 ~]$

我知道类型不同,比较需要两个相似的类型,但最终,它正在比较 -10 。不是吗?

最佳答案

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/

相关文章:

c - 断言在字符串数组比较中失败

javascript - 从 node.js 缓冲区中读取精度损失的 int64

go - strconv.Itoa64(1234) 在 golang 中给出 undefined

c++ - 如何从字符串中提取特定元素?

c++ - Josuttis 书中的 PersonSortCriterion(第一版与第二版)

c - 为什么下面的代码给出了第一个手机号码。不论名字

ios - 将 String 转换为 Int64 导致 32 位设备崩溃

c++ - 该值被复制而不是被 move 。为什么?

c++ - 在 C++ 中验证控制台输入

c++ - 在 C++ 中检查 vector 的所有元素是否相等