Search code examples
c++operators

Why does == work and = does not in an if statement?


for (unsigned int i = 0; i < list.size(); i++) {
        if (list.at(i) = n) {
    cout << "True";
        return 0;
      }}

I was wondering why this would not work I understand that tou should use list.at(i) == n. However i thought that a single = means assigning, and a double == means equal to. I understand it is different but wouldn't using only one = still be correct when using it in an if statement?


Solution

  • It would not necessarily be correct. When you use an assignment expression as a boolean for integers, it will return true if the integer is not zero, and it will return false if the integer is zero.

    Suppose our list looks like this: 1, 2, 0, 5. Now, suppose we have this if-statement:

    if (list.at(0) = 1) {
        cout << "True";
    }
    

    Since the 1 in list.at(0) = 1 is not 0, the if-condition will be satisfied. If we used ==, it would be satisfied since the first value is indeed 1.

    Now let's suppose we have this if-statement:

    if (list.at(1) = 3) {
        cout << "True";
    }
    

    The "True" would be printed because 3 is not equal to 0. However, if we replaced = with ==, the "True" would not be printed since the second value is not 3.

    Let's look at one last example.

    if (list.at(2) = 0) {
        cout << "True";
    }
    

    This would not print out "True" since we are assigning list.at(2) to 0. However, if we replaced the = with ==, the "True" would be printed since the third value in the list is actually 0.

    This shows that = cannot be used as ==.

    P.S. And, if you wanted to use the list later, your list would be modified into a different list.