Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two chars and adding them to a string [duplicate]

Tags:

c++

#include <iostream>
#include <string>

int main() { 
    char s2;
    s2 = '1' - '0';
    std::cout << s2;
    std::cout << std::endl;
    std::cout << '1' - '0';
    std::cin >> s2;
}

The output produced is:

☺
1

My question is, why are the two lines different? I expected and wanted both results to be 1. By my understanding they should be the same but that is obviously wrong, could somebody please explain this to me? Thank you

like image 780
197 Avatar asked Dec 27 '22 06:12

197


1 Answers

why are the two lines different?

The type of the first expression (s2) is char. The type of the second ('1' - '0') is int.

This is why they are rendered differently even though they have the same numeric value, 1. The first is displayed as ASCII 1, whereas the second is displayed as the number 1.

If you are wondering why '1' - '0' gives an int, see Addition of two chars produces int

like image 117
NPE Avatar answered Dec 28 '22 19:12

NPE