When incrementing chars for example: char character{'a'}; is 'a' and as an INT is 97. When I say "character + 1" or "a + 1" I will get the integer value 98 not 'b'. Now if I do "++character" I will get the char 'b'.
char character{'a'};
cout << character + 1 << '\n';
cout << ++character << '\n';
Addition and the increment operator are specified differently in terms of the types involved.
[expr.add]
1 The additive operators + and - group left-to-right. The usual arithmetic conversions are performed for operands of arithmetic or enumeration type.
The usual arithmetic conversions turn every integral type smaller than an int into an int. There's no stopping it, it's baked into the language. And because those conversions happen before the addition itself, the result type cannot be smaller than int. And so character + 1 is int that gets printed by the operator<<(int) overload of the standard stream class.
For increments, however:
[expr.pre.incr]
1 The operand of prefix ++ is modified by adding 1. The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field.
The result ++character is of the same type as character, i.e. it remains a char. It's also an assignable expression (an lvalue) that refers to character. Assigning to it is the same as assigning to character. The result is therefore a char that gets printed by the operator<<(char) overload of the standard stream class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With