Search code examples
c++integeroverflowsizeof

unsigned long larger than 0xFFFFFFFF


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;
}

Solution

  • 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