#include<stdio.h>
int main()
{
if(sizeof(double) > -1)
printf("M");
else
printf("m");
return 0;
}
Size of double
is greater than -1, so why is the output m
?
#include<stdio.h>
int main()
{
if(sizeof(double) > -1)
printf("M");
else
printf("m");
return 0;
}
Size of double
is greater than -1, so why is the output m
?
This is because sizeof(double)
is of type size_t
, which is an implementation-defined unsigned integer type of at least 16 bits. See this for info on sizeof
in C. See this for more info on size_t
The -1
gets converted to an unsigned type for the comparison (0xffff...
), which will always be bigger than sizeof(double)
.
To compare to a negative number, you can cast it like this: (int)sizeof(double) > -1
. Depending on what your objective is, it may also be better to compare to 0
instead.
Your code has implementation defined behavior: sizeof(double)
has type size_t
, which is an unsigned type with at least 16 bits.
If this type is smaller than int
, for example if size_t
has 16 bits and int
32 bits, the comparison would be true because size_t
would be promoted to int
and the comparison would use signed int arithmetics.
Yet on most current platforms, size_t
is either the same as unsigned
or even larger than unsigned
: the rules for evaluating the expression specify that the type with the lesser rank is converted to the type with the higher rank, which means that int
is converted to the type of size_t
if it is larger, and the comparison is performed using unsigned arithmetics. Converting -1
to an unsigned type produces the largest value of this type, which is guaranteed to be larger than the size of a double
, so the comparison is false on these architectures, which is alas very confusing.
I have never seen an architecture with a size_t
type smaller than int
, but the C Standard allows it, so your code can behave both ways, depending on the characteristics of the target system.