C++ Type Modifiers

Type modifiers in C++ are keywords that modify the size or sign of basic data types. The most commonly used modifiers are signed, unsigned, short, and long.

1. Common Type Modifiers

  • signed - Allows both positive and negative values.
  • unsigned - Allows only positive values (increases positive range).
  • short - Reduces memory size.
  • long - Increases memory size.

2. signed and unsigned

The signed modifier allows storing both negative and positive numbers, while unsigned allows only non-negative numbers.

C++
Example of signed and unsigned integers
#include <iostream>
using namespace std;

int main() {
    signed int a = -10;
    unsigned int b = 10;

    cout << "Signed value: " << a << endl;
    cout << "Unsigned value: " << b << endl;

    return 0;
}

3. short Modifier

The short modifier reduces the size of an integer (usually 2 bytes). It is useful when memory optimization is needed.

C++
Example of short integer
#include <iostream>
using namespace std;

int main() {
    short int num = 32000;
    cout << "Short Integer: " << num;
    return 0;
}

4. long Modifier

The long modifier increases the storage capacity of integers. It is used when larger values need to be stored.

C++
Example of long and long long
#include <iostream>
using namespace std;

int main() {
    long int population = 8000000;
    long long int distance = 9223372036854775807;

    cout << "Population: " << population << endl;
    cout << "Distance: " << distance << endl;

    return 0;
}

5. Size and Range Overview

The actual size of modified types depends on the compiler and system architecture, but commonly:

  • short int: 2 bytes
  • int: 4 bytes
  • long int: 4 or 8 bytes
  • long long int: 8 bytes
  • unsigned types: Same size as signed but only positive range

6. Complete Example Program

C++
Program demonstrating all type modifiers
#include <iostream>
using namespace std;

int main() {
    signed int a = -100;
    unsigned int b = 100;
    short int c = 20000;
    long int d = 1000000;
    long long int e = 900000000000;

    cout << "Signed: " << a << endl;
    cout << "Unsigned: " << b << endl;
    cout << "Short: " << c << endl;
    cout << "Long: " << d << endl;
    cout << "Long Long: " << e << endl;

    return 0;
}

Conclusion

Type modifiers in C++ help control the size and range of numeric data types. Using signed, unsigned, short, and long properly ensures efficient memory usage and prevents overflow errors in programs.