Home > OS >  something weird when compare in c
something weird when compare in c

Time:11-25

first, sorry everyone because my bad at english. I have a simple code:

#include <iostream>
using namespace std;
int main(void) {
    char ch = '1';  
    if (ch == (char)1) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    system("pause");
}

the weird thing is the console print No. Why the aren't equal?

CodePudding user response:

ch contains the character code for the character '1'. Assuming ASCII encoding, the value of this code is 49. This is not equal to 1, so the condition is false.

Casting the value 1 to char does not convert it to a character encoding.

For the condition to be true, you need to use the character constant to do the comparison.

if (ch == '1') {

CodePudding user response:

That's because (char)1 is not '1' but represents 'start of heading'. Hence your output became No.

CodePudding user response:

(char) 1 will convert 1 from decimal to ascii code 1 that equals with [start of heading] you can convert '1' ascii code that is 49.

  • Related