11 Beginner The Hundred
The Integer That Prints a Letter
int8_t is not what it says on the tin
#include <cstdint>
#include <iostream>
int main() {
int8_t a = 65;
uint8_t b = 66;
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "a + b = " << a + b << "\n";
}
Run it. What does it print?
Why¶
On every major platform, int8_t is a typedef for signed char and uint8_t for
unsigned char — the <cstdint> names change nothing about the type itself. Overload
resolution sees a character type, so operator<< picks the character overload and
prints the byte as ASCII: 65 is 'A', 66 is 'B'. The sum escapes because a + b
promotes both operands to int before adding, and int gets the numeric overload.
Input is broken the same way: std::cin >> a reads exactly one character, so typing
7 stores 55, the ASCII code of '7'; read into an int instead.
The fix¶
Promote to a real integer before printing:
std::cout << +a << "\n"; // unary plus promotes to int — prints 65
std::cout << static_cast<int>(b) << "\n"; // says what it means — prints 66
Takeaway: int8_t and uint8_t are chars in disguise — promote (+n or a cast)
before streaming them.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo