What is the difference between unsigned long and unsigned long long?

11,147

Solution 1

They're two distinct types, even if they happen to have the same size and representation in some particular implementation.

unsigned long is required to be at least 32 bits. unsigned long long is required to be at least 64 bits. (Actually the requirements are stated in terms of the ranges of values they can represent.)

As you've seen, this is consistent with them both being the same size, as long as that size is at least 64 bits.

In most cases, the fact that they're distinct types doesn't matter much (except that you can't depend on them both having the same range of values). For example, you can assign an unsigned long long to an unsigned long object, and the value will be converted implicitly, possibly with some loss of information. Similarly, you can pass an unsigned long long argument to a function expecting an unsigned long (unless the function is variadic, like printf; then an explicit conversion is needed).

But one case where it does matter is when you have pointers. The types unsigned long* and unsigned long long* are not just distinct, they're not assignment-compatible, because there is no implicit conversion from one to the other. For example, this program:

int main()
{   
    unsigned long*      ulp  = 0;
    unsigned long long* ullp = 0;
    ulp = ullp; // illegal
}

produces the following when I compile it with g++:

c.cpp: In function ‘int main()’:
c.cpp:5:11: error: cannot convert ‘long long unsigned int*’ to ‘long unsigned int*’ in assignment

One more difference: the C++ standard didn't add the long long and unsigned long long types until 2011. C added them with the 1999 standard, and it's not uncommon for pre-C++2011 (and pre-C99) compilers to provide them as an extension.

Solution 2

It is implementation defined as iammilind pointed see How many bytes is unsigned long long? for more details

Share:
11,147
cppcoder
Author by

cppcoder

Updated on June 27, 2022

Comments

  • cppcoder
    cppcoder about 2 years

    I expected that the size will be different. But both are showing 8bytes.

    #include <iostream>
    using namespace std;
    int main()
    {
        cout<<"Size of long:"<<sizeof(unsigned long)<<"\n";
        cout<<"Size of Long Long:"<< sizeof(unsigned long long)<<"\n";
    }
    
    Output:
    Size of long:8
    Size of Long Long:8