Why is sizeof(int) less than -1? [duplicate]

人走茶凉 提交于 2019-11-28 12:04:30

问题


In the following code

#include <stdio.h>

int main()
{
   if (sizeof(int) > -1)
       printf("True");
   else
       printf("False");
return 0;
}

I get the output as "False" rather than "True".My understanding is that sizeof operator just returns the size of int which will be 4 in this case.

Why is the condition evaluated as false?


回答1:


sizeof generates a size_t which is always positive. You are comparing it with -1 which is probably promoted in size_t which gave you a HUGE number, most likely greater than the size of an int.

To make sure of it, try this:

printf("%zu\n", sizeof(int));
printf("%zu\n", (size_t)(-1));

[EDIT]: Following comments (some have been removed), I precise indeed that sizeof is an operator, not a function.




回答2:


From the standard, C11, 6.5.3.4 The sizeof and _Alignof operators:

5 The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in (and other headers).

So, the sizeof operator yields an unsigned value. You then compare an unsigned value with a signed value. That is dealt with by converting the signed value to be unsigned, which explains the behaviour that you see.




回答3:


First, running your code:

cc1plus: warnings being treated as errors
In function 'int main()':
Line 3: warning: comparison between signed and unsigned integer expressions

Then fixing it:

int main()
{
   if ((int)sizeof(int) > -1) // cast value of sizeof(int) to int before compare to int
       printf("True");
   else
       printf("False");
   return 0;
}

Result:

True


来源:https://stackoverflow.com/questions/24797843/why-is-sizeofint-less-than-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!