Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof(unsigned double) equal to 4?

A colleague of mine asked if there is unsigned double, and I said there isn't, but I still checked it, and this compiles in Microsoft Visual C++ 2010:

unsigned double a; double b; printf("size_a=%d size_b=%d", (int) sizeof(a), (int) sizeof(b)); 

It outputs size_a=4 size_b=8. That is, four bytes for unsigned double, and eight bytes for double.

like image 639
sashoalm Avatar asked Feb 20 '13 10:02

sashoalm


People also ask

Is there such thing as unsigned double?

You can not have unsigned floating point types. Therefore no unsigned double or unsigned float. unsigned can only be applied to integer types like char short int and long. The reason we have unsigned integers is that they can store numbers twice as large, and can be better suited for handling binary data.

Why is int 4 bytes?

So the reason why you are seeing an int as 4 bytes (32 bits), is because the code is compiled to be executed efficiently by a 32-bit CPU. If the same code were compiled for a 16-bit CPU the int may be 16 bits, and on a 64-bit CPU it may be 64 bits.

What is unsigned long long?

An unsigned version of the long long data type. An unsigned long long occupies 8 bytes of memory; it stores an integer from 0 to 2^64-1, which is approximately 1.8×10^19 (18 quintillion, or 18 billion billion). A synonym for the unsigned long long type is uint64 .


2 Answers

unsigned double is invalid. This is also true in MSVC. When compiling the above code in MSCV 2010 with warnings enabled you get:

warning C4076: 'unsigned' : can not be used with type 'double'

The compiler actually ignores double after unsigned, making your a actually an unsigned int.

If you try the following:

unsigned double a = 1.0; 

You actually get two warnings:

warning C4076: 'unsigned' : can not be used with type 'double' warning C4244: 'initializing' : conversion from 'double' to 'unsigned int', possible loss of data 

Interestingly, there is no C4076 warning in MSDN for VS2010. It is present only for VS2005 and VS2008.

like image 184
CygnusX1 Avatar answered Oct 15 '22 12:10

CygnusX1


If you set the warning level higher (/W3 in my test), you will get an appropriate warning:

warning C4076: 'unsigned' : can not be used with type 'double'

If you then use the debugger to inspect the variable, all becomes clear:

enter image description here

You can see that the variable is in fact an unsigned int

like image 20
Clifford Avatar answered Oct 15 '22 14:10

Clifford