Search code examples
ctypesintegerc99

Integer types with defined width


I am reading C in a Nuttshell came across a topic Integer types with exact width (C99) enter image description here

Can somebody please explain me what is the use of this data-types

Where can i use this data-types in code

Why this data-types have been introduced

I am a beginner in C programming


Solution

  • C is now a rather old language (since the early 1970s) and compatibility has always be a concern. In those old times, size of integers could be different on different architectures. As a result sizeof(int) is still an implementation detail. What is required by standard:

    • char is the smallest memory unit and has at least 8 bits - all other types have a size that is a multiple of the size of char
    • short has at least 16 bits
    • int is at least as large as short and has at least 16 bits
    • long is at least as large as int and has as least 32 bits
    • long long is at least as large as long and has as least 64 bits

    But for example, you cannot know what is the most appropriate type to process 32 bits values. That's the reason why integer types with exact (or minimal) width were invented.

    For portability reasons, C language make no assumption on the underlying machine, that's the reason why types with exact width are optional. That being said, that are present on all common architectures.


    References: Drafts n1256 for C99 and n1570 for C11 give minimal sizes that an implementation can replace with greater values in 5.2.4.2.1 Sizes of integer types

    The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR_BIT and MB_LEN_MAX, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.

    • number of bits for smallest object that is not a bit-field (byte)
      CHAR_BIT 8

    ...

    • maximum value for an object of type unsigned short int
      USHRT_MAX 65535 // 216 - 1

    ...

    • maximum value for an object of type unsigned int
      UINT_MAX 65535 // 216 - 1

    ...

    • maximum value for an object of type unsigned long int
      ULONG_MAX 4294967295 // 232 - 1

    ...

    • maximum value for an object of type unsigned long long int
      ULLONG_MAX 18446744073709551615 // 264 - 1