Skip to the content of the web site.

Lesson 226: Why doesn't a < b < c; work?

Previous lesson Next lesson


Up until now, we have always combined Boolean-valued operators with logical operators, so while in mathematics courses, you are welcome to write

$a < b < c$;

for example, you may wish to require that $x$ appears on the interval $[0, 1]$, in which case, you would write

$0 \le x \le 1$.

We have, to this point, encoded such a condition as

	if ( (0 <= x) && (x <= 1) ) {
		// Do something...
	}

If, however, you were to accidentally encode this as

	if ( 0 <= x <= 1 ) {
		// Do something...
	}

rather than getting a compile time error, it would happily compile, and whenever $0 \le x \le 1$, it would indeed evaluate to true. The problem is, however, that this evaluates to true for all values of x.

If, however, you were less fortunate, and were to incorrectly code $-1 < x < 1$ as

	if ( -1 < x < 1 ) {
		// Do something...
	}

you would find that this evaluates to true whenever $x \le -1$ and false otherwise!

Again, this is a consequence of the compiler interpreting operators from left to right, and the fact that the compiler will treat true as 1 and false as 0.

In this second example, we have

	if ( -1 < x < 1 ) {
		// Do something...
	}

Recall that while usually we see Boolean-valued operators and logical operators in the context of a conditional statement; for example,

	if ( (-1 < x) < 1 ) {
		// Do something...
	}

If $-1 < x$ or $x > -1$, the first Boolean-valued operator evaluates to true, in which case, we are left with

	if ( 1 < 1 ) {
		// Do something...
	}

and 1 < 1 always evaluates to false. On the other hand, if $-1 \ge x$ or $x \le -1$, the first Boolean-valued operator evaluates to false, in which case, we are left with

	if ( 0 < 1 ) {
		// Do something...
	}

and 0 < 1 always evaluates to true.

In general, this author knows of no situations where you may ever want to purposely use the output of one comparison operator as an operand of another comparison operator; consequently, if you ever see code like this, it is either a) the work of a mischievous mind perhaps having spent too much time reading entries to the Obfuscated C contest or b) the source of a bug. In either case, determine what was actually meant and correct it.


Previous lesson Next lesson