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
shortis 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
ais a signedshort, capable of holding both positive and negative values. - The variable
buses the optionalintspecifier, which does not change its behavior. - The variable
cis 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
shortxis initialized to its maximum value,32767. - Adding 1 to
xcauses an overflow, wrapping the value around to the minimum of the range,-32768. - The unsigned
shortyis initialized to its maximum value,65535. - Adding 1 to
ycauses an overflow, wrapping the value around to0.
Key Points about short Keyword
- The
shortkeyword 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,768to32,767for signed and0to65,535for unsigned. - The optional
intspecifier can be used, but it does not change the behavior ofshort. - Use
shortto save memory when the full range ofintis not required.
