Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'a' == 'b'. It's a good way to do?

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?

like image 621
Overflowh Avatar asked Nov 30 '11 18:11

Overflowh


2 Answers

you can absolutely securely compare fundamental types by comparison operator ==

like image 68
triclosan Avatar answered Nov 12 '22 15:11

triclosan


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'.)

like image 13
Ted Hopp Avatar answered Nov 12 '22 16:11

Ted Hopp