Why does the output format of an int8_t use 4 bytes?

Why is the output format of an int8_t uses 4 bytes?

It doesn't. You're outputting an int, not a int8_t.


To stream a uint8_t to std::cout with lexical conversions, you have correctly used + to trigger a promotion to int (needed because char and related types do not undergo lexical conversion with IOstreams).

But then… you've promoted it to int. So you see int-like things.

Your second line is good and ensures you don't fall foul of sign extension.


The problem is that you use the unary arithmetic operator + which performs integer promotion. So your int8_t is promoted to an integer. Which with your compiler and set up is 32 bits.

The built-in unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts char to int or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion.

Source: https://en.cppreference.com/w/cpp/language/operator_arithmetic

The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand.

Source C++ Standard § 8.3.1.7

Tags:

C++