Why is sizeof(int) less than

This question already has an answer here:

  • void main() { if(sizeof(int) > -1) printf(“true”); else printf(“false”); ; [duplicate] 3 answers

  • 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("%zun", sizeof(int));
    printf("%zun", (size_t)(-1));
    

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


    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.


    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
    
    链接地址: http://www.djcxy.com/p/21146.html

    上一篇: 操作“false <true”的定义良好吗?

    下一篇: 为什么sizeof(int)小于