Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use short instead of int?

Tags:

c

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 that's exactly 16 bits in size

In the first case, since int is guaranteed to be at least 16 bits and is the most efficient integral data type, I would use int. In the second case, since the standard doesn't guarantee that short's size is exactly 16 bit, I would use int16_t instead. So what use is short?

like image 529
manny Avatar asked Apr 20 '12 22:04

manny


People also ask

What is the difference between short and int?

short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.

Is short faster than int?

Thus, operations on char/short/int are generally equally fast, as the former ones are promoted to the latter.

Is short int same as int?

short and int must be at least 16 bits, long must be at least 32 bits, and that short is no longer than int, which is no longer than long. Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits. Save this answer.

Why use short data types?

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte , the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.


1 Answers

There is never a reason to use short in a C99 environment that has 16-bit integers; you can use int16_t, int_fast16_t or int_least16_t instead.

The main reasons for using short is backward compatibility with C89 or older environments, which do not offer these types, or with libraries using short as part of their public API, for implementing <stdint.h> itself, or for compatibility with platforms that do not have 16-bit integers so their C compilers do not provide int16_t.

like image 198
Fred Foo Avatar answered Oct 11 '22 15:10

Fred Foo