What happens if I compare two characters in this way:
if ('a' == 'b')
doSomething();
I’m really curious to know what the language (and the compiler) does when it finds a comparison like this. And, of course, if it is a correct way to do something, or if I have to use something like strcmp().
EDIT
Wait wait.
Since someone haven’t understood what I really mean, I decided to explain in another way.
char x, y;
cout << "Put a character: ";
cin >> x;
cout << "Put another character: ";
cin >> y;
if (x == y)
doSomething();
Of course, in the if brackets you can replace == with any other comparison operator.
What really I want to know is: how the character are considered in C/C++? When the compiler compares two characters, how does it know that ‘a’ is different than ‘b’? It refers to the ASCII table?
In C and C++, single character constants (and
charvariables) are integer values (in the mathematical sense, not in the sense ofintvalues). The compiler compares them as integers when you use==. You can also use the other integer comparison operators (<,<=, etc.) You can also add and subtract them. (For instance, a common idiom to change a digit character into its numerical value isc - '0'.)