What is the difference between unsigned length and unsigned long?
I expected the size to be different. But both show 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 are two different types, even though they are the same size and representation in some particular implementation.
unsigned long
at least 32 bits are required. unsigned long long
at least 64 bits are required. (In fact, requirements are specified in terms of the ranges of values they can represent.)
As you saw, this is consistent with both being the same size if that size is at least 64 bits.
In most cases, the fact that they are different types does not really matter (except that you cannot depend on them for the same range of values). For example, you can assign to an unsigned long long
object unsigned long
and the value will be implicitly converted, possibly with some loss of information. Similarly, you can pass an argument to a unsigned long long
function expecting unsigned long
(if the function is not a variable, for example printf
, then an explicit conversion is required).
But one case where it matters is when you have pointers. The types unsigned long*
and are unsigned long long*
not just different, they are not compatible with the purpose 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
Another difference: Standard C ++ does not add types long long
and unsigned long long
up to 2011. C added them to the 1999 standard, and it's not uncommon for pre-C ++ 2011 (and pre-C99) to provide them as an extension.
This is an implementation defined as iammilind point see How many unsigned bytes are long long? for more details
The standard states that it long long
must be at least the same size as long
, or larger. Accordingly, for types unsigned
, long
and int
.
Actual values are implementation and hardware dependent.