c++visual-studio-2010

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.


Solution

  • 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.