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
They’re two distinct types, even if they happen to have the same size and representation in some particular implementation.
unsigned longis required to be at least 32 bits.unsigned long longis 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 longto anunsigned longobject, and the value will be converted implicitly, possibly with some loss of information. Similarly, you can pass anunsigned long longargument to a function expecting anunsigned long(unless the function is variadic, likeprintf; then an explicit conversion is needed).But one case where it does matter is when you have pointers. The types
unsigned long*andunsigned 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:produces the following when I compile it with g++:
One more difference: the C++ standard didn’t add the
long longandunsigned long longtypes 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.