c++ - unsigned long 大于 0xFFFFFFFF

标签 c++ integer overflow sizeof

如果 unsigned long 最大值为 4294967295,测试程序如何得出 4294967297?

#include <iostream>
using namespace std;
unsigned long millis_diff(unsigned long then, unsigned long now) {
    return now < then ? now + then : now - then;
}
int main()
{
    unsigned long now = 2;
    unsigned long then = 4294967295; //unsigned long maximum value
    unsigned long diff = millis_diff(then, now);
    cout << diff;
    return 0;
}

最佳答案

原因是编译器定义 unsigned long int 的方式似乎与定义 unsigned long long int 的方式相同。:)

这是一个演示程序

#include <iostream>
#include <limits>

int main()
{
    std::cout << "sizeof( unsigned long ) = " << sizeof( unsigned long ) << '\n';
    std::cout << "The maximum values is " << std::numeric_limits<unsigned long>::max() << '\n';
}

它的输出是

sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615

关于c++ - unsigned long 大于 0xFFFFFFFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044616/

相关文章:

c++ - 在特定目录 C++ 中按扩展名搜索

c++ - 合并 2 个文件并对它们进行排序

string - 使用空接口(interface)更改函数中的 arg

java - 09 在 9 被识别的地方不被识别

opengl - 无法获得在 GLSL 1.5 中工作的整数顶点属性

javascript - 如何将<table>拆分成多个<div>?

c++ - 你能使用 constexpr 变量的地址吗?

c++ - 为什么必须在注册过滤器时声明引脚?

html - 子元素水平溢出时,为什么忽略了父元素的右填充?

CSS 右负边距