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?
you can absolutely securely compare fundamental types by comparison operator ==
In C and C++, single character constants (and char
variables) are integer values (in the mathematical sense, not in the sense of int
values). 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 is c - '0'
.)
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