Why is sizeof(unsigned double) equal to 4?

Solution 1:

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.

Solution 2:

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

Solution 3:

Combining unsigned with double in the declaration specifier sequence is not valid C++. This must be an MSVC extension (or bug) of some sort.

As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a type-specifier-seq or trailing-type-specifier-seq. The only exceptions to this rule are the following:

  • const can be combined with any type specifier except itself.
  • volatile can be combined with any type specifier except itself.
  • signed or unsigned can be combined with char, long, short, or int.
  • short or long can be combined with int.
  • long can be combined with double.
  • long can be combined with long.