When to use short instead of int?

前端 未结 5 1659
梦如初夏
梦如初夏 2021-02-08 11:46

Two use cases for which I would consider short come to mind:

  1. I want an integer type that\'s at least 16 bits in size
  2. I want an integer type t
5条回答
  •  抹茶落季
    2021-02-08 12:04

    ISO/IEC 9899:1999 (C99) adds headers and that provide what you need:

    • int16_t might not be defined, but if there is a 16-bit (exactly) integer type in the implementation, int16_t will be an alias for it.
    • int_least16_t is a type that is the smallest type that holds at least 16 bits. It is always available.
    • int_fast16_t is the fastest type that holds at least 16 bits. It is always available.

    Similarly for other sizes: 8, 16, 32, 64.

    There's also intmax_t for the maximum precision integer type. Of course, there's also an unsigned type for each of these: uint16_t etc.

    These types are also present in C2011. They were not present in C89 or C90. However, I believe that the headers are available in some shape or form for most compilers, even those like MS Visual C, that do not claim to provide support for C99.

    Note that I've given links to the POSIX 2008 versions of the and headers. POSIX imposes rules on the implementation that the C standard does not:

    §7.18.1.1 Exact-width integer types

    ¶1 The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

    ¶2 The typedef name uintN_t designates an unsigned integer type with width N. Thus, uint24_t denotes an unsigned integer type with a width of exactly 24 bits.

    ¶3 These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, it shall define the corresponding typedef names.

提交回复
热议问题