What is the difference between “short int” and “int” in C?

后端 未结 9 2010
闹比i
闹比i 2020-12-24 07:22

How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?

相关标签:
9条回答
  • 2020-12-24 07:55

    Actually everything depends on compiler and system both. But the basic rule says that int can never be less than short and can never be greater than long.

    short <= int <= long

    0 讨论(0)
  • 2020-12-24 07:56

    "A short integer in one programming language may be a different size in a different language or on a different processor. In some languages this size is fixed across platforms, while in others it is machine-dependent. In some languages this datatype does not exist at all."

    Source

    0 讨论(0)
  • 2020-12-24 07:56

    I was working on the same today. My conclusion is it depends on the word length of the machine architecture on which your program is getting executed. As per C99 limits.h documentation.

    /* Minimum and maximum values a `signed short int' can hold.  */
    #  define SHRT_MIN  (-32768)
    #  define SHRT_MAX  32767
    
    /* Maximum value an `unsigned short int' can hold.  (Minimum is 0.)  */
    #  define USHRT_MAX 65535
    
    /* Minimum and maximum values a `signed int' can hold.  */
    #  define INT_MIN   (-INT_MAX - 1)
    #  define INT_MAX   2147483647
    
    /* Maximum value an `unsigned int' can hold.  (Minimum is 0.)  */
    #  define UINT_MAX  4294967295U
    
    /* Minimum and maximum values a `signed long int' can hold.  */
    #  if __WORDSIZE == 64
    #   define LONG_MAX 9223372036854775807L
    #  else
    #   define LONG_MAX 2147483647L
    #  endif
    #  define LONG_MIN  (-LONG_MAX - 1L)
    
    /* Maximum value an `unsigned long int' can hold.  (Minimum is 0.)  */
    #  if __WORDSIZE == 64
    #   define ULONG_MAX    18446744073709551615UL
    #  else
    #   define ULONG_MAX    4294967295UL
    #  endif
    

    Let me know if anyone has better answer.

    0 讨论(0)
  • 2020-12-24 08:10

    In theory/by the C standard, they could be of any size as long as 16 bit <= short <= int.

    In the real world, this is how the sizes are implemented.

    CPU             short   int
    8 bit           16      16
    16 bit          16      16
    32 bit          16      32
    64 bit          16      32
    
    0 讨论(0)
  • 2020-12-24 08:12

    Never rely on a datatype being a given size in C. Always check the bounds in limits.h if in doubt.

    0 讨论(0)
  • 2020-12-24 08:14

    They may have the same size, but it is guaranteed that int is equal to or bigger than short int.

    0 讨论(0)
提交回复
热议问题