Is the size of C “int” 2 bytes or 4 bytes?

后端 未结 13 2707
不知归路
不知归路 2020-11-22 10:52

Does an Integer variable in C occupy 2 bytes or 4 bytes? What are the factors that it depends on?

Most of the textbooks say integer variables occupy 2 bytes. But whe

13条回答
  •  旧时难觅i
    2020-11-22 11:05

    Is the size of C “int” 2 bytes or 4 bytes?

    Does an Integer variable in C occupy 2 bytes or 4 bytes?

    C allows "bytes" to be something other than 8 bits per "byte".

    CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

    A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

    #include 
    printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);
    

    What are the factors that it depends on?

    The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

    minimum value for an object of type int INT_MIN -32767
    maximum value for an object of type int INT_MAX +32767
    C11dr §5.2.4.2.1 1

    The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

    The computer's processor and architecture drive the int bit size selection.

    Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).

提交回复
热议问题