There are several common scenarios where using smaller integer types makes sense. Here are some practical examples:
In games, you often need to store information for lots of objects. For example, if you're making a role-playing game, you might have stats for each character:
#include <iostream>
using namespace std;
int main() {
// Using regular int for everything (wasteful)
int Health{100}; // 4 bytes
int Level{1}; // 4 bytes
int Strength{15}; // 4 bytes
int Intelligence{12}; // 4 bytes
// Total: 16 bytes per character
// Using appropriate sizes
// 2 bytes (max 32,767 is plenty)
int16_t BetterHealth{100};
// 1 byte (max 127 is enough)
int8_t BetterLevel{1};
// 1 byte (max 127 is enough)
int8_t BetterStrength{15};
// 1 byte (max 127 is enough)
int8_t BetterIntelligence{12};
// Total: 5 bytes per character
// If your game has 1000 characters, you save:
cout << "Memory saved per 1000 characters: "
<< (16 - 5) * 1000 << " bytes";
}
Memory saved per 1000 characters: 11000 bytes
In graphics programming, colors are often stored as RGB values from 0-255, making uint8_t
 perfect:
#include <iostream>
using namespace std;
int main() {
// Each color component only needs
// values 0-255
uint8_t Red{255}; // Perfect fit!
uint8_t Green{128};
uint8_t Blue{64};
// Using regular int would waste 3 bytes
// per color component!
// Uses 4 bytes instead of 1
int WastefulRed{255};
int WastefulGreen{128};
int WastefulBlue{64};
cout << "Memory used for one color"
" (efficient): "
<< sizeof(Red) + sizeof(Green) + sizeof(Blue)
<< " bytes\n";
cout << "Memory used for one color"
" (wasteful): "
<< sizeof(WastefulRed)
+ sizeof(WastefulGreen)
+ sizeof(WastefulBlue)
<< " bytes";
}
Memory used for one color (efficient): 3 bytes
Memory used for one color (wasteful): 12 bytes
When programming small devices (like Arduino), memory is very limited. Using smaller types can be the difference between your program fitting in memory or not!
Remember though - don't use smaller types just because you can. Only use them when you:
Most of the time, using regular int
is fine and makes your code simpler and safer.
Answers to questions are automatically generated and may not have been reviewed.
Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.