wiki:cpp-integer-promotions
Table of Contents
C++ Integer promotions
Integer promotions are automatic type conversions where smaller integer types (bool, char, short) are converted to int or unsigned int in arithmetic operations. This is an implicit conversion rule from the C standard that C++ inherits, often causing surprises when arithmetic on char or short unexpectedly produces int.
Be aware that arithmetic on char or short produces int; use explicit casts if you need different types.
Example
This example shows integer promotions in arithmetic operations.
// compile: g++ -o promote promote.cpp // run: ./promote // description: integer promotions convert small types to int #include <iostream> #include <typeinfo> int main() { char c = 'A'; short s = 10; auto result_c = c + 1; // char promoted to int auto result_s = s + 1; // short promoted to int std::cout << "sizeof(char): " << sizeof(char) << "\n"; std::cout << "sizeof(c + 1): " << sizeof(result_c) << "\n"; std::cout << "Type: " << typeid(result_c).name() << "\n"; // Result is int, not char std::cout << "c + 1 = " << result_c << "\n"; return 0; }
wiki/cpp-integer-promotions.md · Last modified: by 127.0.0.1
