<分区>
unsigned long mynum = 7;
if(mynum > -1) // false
为什么会这样?是不是因为 -1 是一个 int,当它被“提升”为 unsigned long 时,它获得了 unsigned long 的最大值?
<分区>
unsigned long mynum = 7;
if(mynum > -1) // false
为什么会这样?是不是因为 -1 是一个 int,当它被“提升”为 unsigned long 时,它获得了 unsigned long 的最大值?
最佳答案
这可能不对,但这是我的想法:
当你执行下面的代码时
unsigned long a = -8;
std::cout << a;
由于无符号值不能小于 0,因此它将返回无符号长整数的最大值 - 在这种情况下为 8 或 4294967288。
这就是 -1
在转换为 unsigned long 时发生的情况
关于c++ - 为什么将 unsigned long 与负数进行比较会导致 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39872325/
相关文章:
c++ - 如何保持服务器运行(cpprestsdk - 卡萨布兰卡)
c++ - 如何将 priority_queue 与类实例的非静态比较方法一起使用?
c++ - 如果初始化需要shared_from_this,如何在一次调用中构建一个类?
c++ - 将 Cmake 与 Qt Creator 一起使用
c++ - shared_ptr 问题从成员函数返回向上转换版本
c++ - arm-none-eabi-g++ 编译器抛出编译错误 pthread_exit 未在此范围内声明
c++ - boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为