Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the type conversion take place without me telling it to do so when doing "character + 1"?

Tags:

c++

ascii

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';
like image 621
Gennady Mason Avatar asked Jan 13 '19 13:01

Gennady Mason


1 Answers

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.

like image 61
StoryTeller - Unslander Monica Avatar answered Nov 14 '22 20:11

StoryTeller - Unslander Monica