Slow Coding #6 - Naming - Example #1 - “=” Error

July 26th, 2009

In C++, there is a kind of error which often looks like this:

if (x = y) …

where the coder meant to type

if (x == y)

The part inside the ellipses in the first example means “set x to the value of y”, while the part inside the ellipses in the second example means “is x the same value as y?”. Oops.

Computer science teachers are quick to blame the coder in this case. The root cause, however, is in a poor choice made by the framers of the C programming conventions.

This situation causes lots of errors in C++ programming. It happens because a symbol, “=” (or the word “equals”), that is ambiguous in more everyday usage (it can have either of the above meanings, among other things) has been imported into a new environment where it is no longer ambiguous, but has a more narrow technical meaning.

It would have been simple for the framers of C++ conventions to avoid this situation, by using (relevantly) unique symbols for both meanings.

For example, “:=” for “set x to the value of y” and “==” for “is x the same value as y?”.

The framers of Pascal committed the same error, but backwards. “:=” means “set x to the value of y”, but “=” means “is x the same value as y?” in that language. So, framers of C and C++, you aren’t alone.

It would be simple to change this convention, by keeping the “=” symbol in C++ (for backward compatibility), but also introducing a new, unique symbol going forward.

Coders unite!

One Response to “Slow Coding #6 - Naming - Example #1 - “=” Error”

  1. Eric Normand says:

    I think you’re right. Those little touches are what makes a language truly a work of art.

    The best alternative I’ve seen for writing “==” is “=?”. It looks different from “:=” and implies a boolean with the question mark.

Leave a Reply