Topic 8 of 83
Type Modifiers
Overview
Type modifiers alter the memory size or range of primitive types. They allow you to optimize memory usage (short) or increase capacity (long, unsigned) based on application needs.
Syntax
cpp
unsigned int positiveOnly = 4000000000; // Cannot hold negative numbers, doubles positive range
short int smallNum = 32000; // Usually 2 bytes
long long hugeNum = 9000000000000LL; // Guaranteed to be at least 64 bits
signed char temp = -120; // Explicitly signedCommon Pitfalls
- Mixing signed and unsigned types in comparisons or arithmetic, which can lead to unexpected type promotion bugs.
- Integer overflow (e.g., adding 1 to the maximum value of a signed int makes it a highly negative number).
Interview Tips
- Explain what happens if an unsigned integer underflows (e.g., unsigned int x = 0; x--;). It wraps around to the maximum possible value.
Real-World Example
Using `unsigned` for sizes or counters that can never be negative.
example
cpp
#include <iostream>
using namespace std;
int main() {
unsigned int population = 8000000000; // Earth's population
cout << "Population: " << population << "\n";
return 0;
}