C++ short Keyword
The short
keyword in C++ is a data type modifier used to declare integer variables with a smaller range of values compared to the default int
. It is primarily used to save memory in programs where the full range of an int
is not needed.
A short
variable typically occupies 2 bytes of memory (16 bits) and can store values in the range of -32,768
to 32,767
(for signed short
) or 0
to 65,535
(for unsigned short
), depending on the platform and compiler.
Syntax
</>
Copy
short variable_name;
short int variable_name; // Optional 'int' specifier
unsigned short variable_name; // For unsigned short integers
- short
- The keyword used to declare a short integer variable.
- int
- An optional specifier, as
short
is implicitly a short integer. - unsigned
- Specifies that the variable will only store non-negative values.
Examples
Example 1: Declaring and Initializing short
Variables
This example demonstrates how to declare and initialize short
variables in C++.
</>
Copy
#include <iostream>
using namespace std;
int main() {
short a = 100; // Signed short
short int b = -200; // Equivalent to 'short'
unsigned short c = 300; // Unsigned short
cout << "Signed short a: " << a << endl;
cout << "Signed short b: " << b << endl;
cout << "Unsigned short c: " << c << endl;
return 0;
}
Output:
Signed short a: 100
Signed short b: -200
Unsigned short c: 300
Explanation:
- The variable
a
is a signedshort
, capable of holding both positive and negative values. - The variable
b
uses the optionalint
specifier, which does not change its behavior. - The variable
c
is an unsignedshort
, allowing it to store only non-negative values.
Example 2: Overflow Behavior of short
This example demonstrates what happens when a short
variable exceeds its range.
</>
Copy
#include <iostream>
using namespace std;
int main() {
short x = 32767; // Maximum value for signed short
cout << "x: " << x << endl;
x = x + 1; // Overflow occurs
cout << "x after overflow: " << x << endl;
unsigned short y = 65535; // Maximum value for unsigned short
cout << "y: " << y << endl;
y = y + 1; // Overflow occurs
cout << "y after overflow: " << y << endl;
return 0;
}
Output:
x: 32767
x after overflow: -32768
y: 65535
y after overflow: 0
Explanation:
- The signed
short
x
is initialized to its maximum value,32767
. - Adding 1 to
x
causes an overflow, wrapping the value around to the minimum of the range,-32768
. - The unsigned
short
y
is initialized to its maximum value,65535
. - Adding 1 to
y
causes an overflow, wrapping the value around to0
.
Key Points about short
Keyword
- The
short
keyword is a data type modifier for declaring smaller integers. - It is typically 2 bytes (16 bits) in size, depending on the platform and compiler.
- It can be signed (default) or unsigned, with a range of
-32,768
to32,767
for signed and0
to65,535
for unsigned. - The optional
int
specifier can be used, but it does not change the behavior ofshort
. - Use
short
to save memory when the full range ofint
is not required.