Programming Fundamentals/Assignment vs Equality

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Overview[edit]

Assignment sets and/or re-sets the value stored in the storage location denoted by a variable name.[1] Equality is a relational operator that tests or defines the relationship between two entities.[2]

Discussion[edit]

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 many programming languages, each data type can be used as a Boolean expression because each data type can be demoted into a Boolean value by using the rule/concept that zero and nothing represent false and all non-zero values represent true.

Within various languages, 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 typically means assignment. To get the equality concept of math we often use two equal symbols to represent the relational operator of equality. Let’s consider:

If (pig = 'y')
    Output "Pigs are good"
Else
    Output "Pigs 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. The correct syntax for a Boolean expression is:

If (pig == 'y')
    Output "Pigs are good"
Else
    Output "Pigs are bad."

This example reminds you that you must be careful in creating your test expressions so that they are indeed a question, usually involving the relational operators. Some programming languages will generate a warning or an error when an assignment is used in a Boolean expression, and some do not.

Don’t get caught using assignment for equality.

Key Terms[edit]

assignment
Sets or resets the value of a variable.
equality
Tests or defines the relationship between values.

References[edit]