Output data type of sizeof() operator

前端 未结 1 1261
别那么骄傲
别那么骄傲 2021-01-11 17:03

I am using Ubuntu 16.04.5 and GCC version 5.4.0.

I was playing with sizeof() operator, wrote the code below:

#include 

i         


        
相关标签:
1条回答
  • 2021-01-11 17:18

    The sizeof operator evaluates to a value of type size_t. This type is unsigned and typically larger than an int, which is why you get the warning.

    Using the wrong format specifier to printf invokes undefined behavior. You can get away with this however for types smaller than int due to the rules of integer promotions in section 6.3.1.1p2 of the C standard:

    The following may be used in an expression wherever an int or unsigned int may be used:

    • An object or expression with an integer type (other than int or unsigned int ) whose integer conversion rank is less than or equal to the rank of int and unsigned int .
    • A bit-field of type _Bool , int , signed int ,or unsigned int .

    If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int ; otherwise, it is converted to an unsigned int . These are called the integer promotions . All other types are unchanged by the integer promotions.

    So as long this doesn't result in a change from unsigned to signed, types smaller than int can be printed with %d.

    The proper type modifier for size_t is %zu, as per section 7.21.6.1p7 of the C standard regarding length modifiers for the fprintf function (and by extension, printf):

    z

    Specifies that a following d , i , o , u , x ,or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to size_t argument.

    So what you want is:

    printf("size of long int is %zu\n", sizeof(mylint));
    
    0 讨论(0)
提交回复
热议问题