samedi 23 décembre 2017

Why is `if (x = 1)` not working like I expect?

I am using equality comparison in if statements. But I find them not working in the way I expect.

For example:

#include <iostream>

int main()
{
    using std::cin;
    using std::cout;

    int x;
    cin >> x;

    if (x = 0) {
        cout << "zero\n";
    }
    else if (x = 1) {
        cout << "one\n";
    }
    else {
        cout << "other\n";
    }
}

I expect it gives output according to my input. But I find it always output "one".

What am I doing wrong? Why is the compiler not telling me?

Aucun commentaire:

Enregistrer un commentaire