0

According to the C++ conversion rules, If for example an int is multiplied by a double then both will be first converted into doubles then the multiplication will be done.

int a = 5;
double b = 0.5;
cout<< a * b; // 2.5

On the other hand, multiplying an int by an int doesn't require converting and the multiplication can be done immediately resulting in an int.

int a = 5;
int b = 5;
cout<< a * b; //25

Applying the these rule, I thought that multiplying a char by a char won't require converting and the multiplication will result in a char (1 byte). Thus, the result will overflow for the following sample

char a = 'a'; // 97
char b = 'b'; // 98
cout<< a * b; // 9506 - Doesn't overflow!

However, this doesn't seem to be the case!
Is there something special about multiplying two characters?.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Amr Keleg
  • 336
  • 4
  • 11
  • 3
    [This question](https://stackoverflow.com/questions/7538448/adding-two-unsigned-char-variables-and-result-is-int) is pretty similar. Does it give you your answer? – chris Mar 02 '19 at 22:31
  • @chris Yes, it does. Thanks a lot. – Amr Keleg Mar 02 '19 at 22:33
  • 3
    [This](https://stackoverflow.com/questions/43530754/type-of-char-multiply-by-another-char) may be of use to you. – asendjasni Mar 02 '19 at 22:34

1 Answers1

1

a char by a char won't require casting and the multiplication will result in a char (1 byte).

no, char is automatically promoted to int or unsigned int

so in

char a = 'a'; // 97
char b = 'b'; // 98
cout<< a * b; // 9506 - Doesn't overflow!

there is no overflow while an int as at least 14 bits, 97 and 98 are promoted from char in positive int whatever the fact a char is signed or not while a char has more than 7 bits. So you compute 97*98 being 9506

bruno
  • 32,421
  • 7
  • 25
  • 37