Skip to main content
Engineering LibreTexts

14.3: Assignment vs Equality within C++

  • Page ID
    10326
  • General Discussion

    Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the while; do while; or for loops) based on the truthfulness or falseness of the expression. Thus, we often talk about the Boolean expression that is controlling the structure. Within many programming languages, this expression must be a Boolean expression and is governed by a tight set of rules. However, in C++ every data type can be used as a Boolean expression, because every data type can be demoted into a Boolean value by using the rule/concept that zero represents false and all non-zero values represent true.

    Within C++ we have the potential added confusion of the equals symbol as an operator that does not represent the normal math meaning of equality that we have used for most of our life. The equals symbol with C++ means: assignment. To get the equality concept of math within C++ we use two equal symbols to represent the relational operator of equality. Let's consider:

    if (pig = 'y')
      {
      cout << "\nPigs are good";
      }
    else
      {
      cout << "\nPigs are bad.";
      } 
    

    The test expression of the control structure will always be true, because the expression is an assignment (not the relational operator of ==). It assigns the 'y' to the variable pig, then looks at the value in pig and determines that it is not zero; therefore the expression is true. And it will always be true and the else part will never be executed. This is not what the programmer had intended. Let's consider:

    do
      {
      cout << "\nPigs are good";
      cout << "\nDo it again, answer y or n: ";
      cin >> do_it_again
      }
    while (do_it_again = 'y');
    

    The loop's test expression will always be true, because the expression is an assignment (not the relational operator of ==). It assigns the 'y' to the variable do_it_again, then looks at the value in do_it_again and determines that it is not zero; therefore the expression is true. And it will always be true and you have just created an infinite loop. As a reminder, infinite loops are not a good thing.

    These examples are to remind you that you must be careful in creating your test expressions so that they are indeed a question usually involving the relational operators.

    Don't get caught using assignment for equality.