Assignment (computer Science) - Assignment Versus Equality

Assignment Versus Equality

A notorious example for a bad idea was the choice of the equal sign to denote assignment. It goes back to Fortran in 1957 and has blindly been copied by armies of language designers. Why is it a bad idea? Because it overthrows a century old tradition to let “=” denote a comparison for equality, a predicate which is either true or false. But Fortran made it to mean assignment, the enforcing of equality. In this case, the operands are on unequal footing: The left operand (a variable) is to be made equal to the right operand (an expression). x = y does not mean the same thing as y = x. —Niklaus Wirth, Good Ideas, Through the Looking Glass

Beginning programmers sometimes confuse assignment with the relational operator for equality, as "=" means equality in mathematics, and is used for assignment in many languages. But assignment alters the value of a variable, while equality testing tests whether two expressions have the same value.

In some languages, such as BASIC, a single equals sign ("=") is used for both the assignment operator and the equality relational operator, with context determining which is meant. Other languages use different symbols for the two operators. For example:

  • In Pascal, the assignment operator is a colon and an equals sign (":=") while the equality operator is a single equals ("=").
  • In C, the assignment operator is a single equals sign ("=") while the equality operator is a pair of equals signs ("==").

The similarity in the two symbols can lead to errors if the programmer forgets which form ("=", "==", ":=") is appropriate, or mistypes "=" when "==" was intended. This is a common programming problem with languages such as C, where the assignment operator also returns the value assigned, and can be validly nested inside expressions (in the same way that a function returns a value). If the intention was to compare two values in an if statement, for instance, an assignment is quite likely to return a value interpretable as Boolean true, in which case the then clause will be executed, leading the program to behave unexpectedly. Some language processors (such as gcc) can detect such situations, and warn the programmer of the potential error.

Read more about this topic:  Assignment (computer Science)

Famous quotes containing the word equality:

    Small natures require despotism to exercise their sinews, as great souls thirst for equality to give play to their heart.
    Honoré De Balzac (1799–1850)