How test program can result 4294967297 if unsigned long maximum is 4294967295?
#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;
}
The reason is that it seems your compiler defines unsigned long int
the same way as it defines unsigned long long int
.:)
Here is a demonstrative program
#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';
}
Its output is
sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615
How test program can result 4294967297 if unsigned long maximum is 4294967295?
Given the premise, it can't.
However, there is no guarantee for unsigned long
maximum to be exactly 4'294'967'295, so your premise may be invalid. that maximum corresponds to the maximum that a 32 bit number can represent. 32 is the minimum required width for (unsigned
) long
, but it may be wider than that.
In particular, it is typical for some 64 bit systems to have unsigned long
of 64 bits, which has the maximum value of 18'446'744'073'709'551'615.
User contributions licensed under CC BY-SA 3.0