This answer is directed in large part at a comment made by @RafałDowgird:
"The minimum size of operations is int." - This would be very strange
(what about architectures that efficiently support char/short
operations?) Is this really in the C++ spec?
Keep in mind that the C++ standard has the all-important "as-if" rule. See section 1.8: Program Execution:
3) This provision is sometimes called the "as-if" rule, because an
implementation is free to disregard any requirement of the Standard
as long as the result is as if the requirement had been obeyed, as far
as can be determined from the observable behavior of the program.
The compiler cannot set an int
to be 8 bits in size, even if it were the fastest, since the standard mandates a 16-bit minimum int
.
Therefore, in the case of a theoretical computer with super-fast 8-bit operations, the implicit promotion to int
for arithmetic could matter. However, for many operations, you cannot tell if the compiler actually did the operations in the precision of an int
and then converted to a char
to store in your variable, or if the operations were done in char all along.
For example, consider unsigned char = unsigned char + unsigned char + unsigned char
, where addition would overflow (let's assume a value of 200 for each). If you promoted to int
, you would get 600, which would then be implicitly down cast into an unsigned char
, which would wrap modulo 256, thus giving a final result of 88. If you did no such promotions,you'd have to wrap between the first two additions, which would reduce the problem from 200 + 200 + 200
to 144 + 200
, which is 344, which reduces to 88. In other words, the program does not know the difference, so the compiler is free to ignore the mandate to perform intermediate operations in int
if the operands have a lower ranking than int
.
This is true in general of addition, subtraction, and multiplication. It is not true in general for division or modulus.
^
is XOR.