One-line `if ... then ...` syntax

I strongly dispute this claim. The introduction of || and && in The C programming language of K&R just says:

The || operator groups left-to-right. It returns 1 if either of its operands compare unequal to zero, and 0 otherwise. Unlike |, || guarantees left-to-right evaluation: the first operand is evaluated, including all side effects; if it is unequal to 0, the value of the expression is 1.

The wikipedia page on short-circuit evaluation says nothing on this. I have a hard time believing that for combining simple relational operators (<, >, ==, and !=) over primitive data, && and || (which may incur in a jump) are more lightweight than | and & (the simplest possible operations to project in a circuit).

On the contrary, && and || short-circuiting behavior are absolutely about semantics. You can see in the K&R quote, they gave a guarantee. If the whole point of && and || was not to be short-circuiting they would not even have a reason to exist, because in C any integer greater than zero counts as true, together with > 0 you could have used | and & as replacements without loss of anything besides the short circuiting behavior.

&& and || make much easier write code like i <= n && a[i] != x, or s.tag == X && s.union_value, or basically any other condition in which the second expression would lead to an access memory violation or undefined behavior if the first expression did not guarantee that it would not. Lots of code rely on this behavior, and I do not believe this is an accident but the original intent of the short-circuiting && and ||.

I had the same experience with the unless and when of Ruby, I always though they were harder to understand than && and ||. This is anecdotal evidence. Your experience is not universal. But I would argue that && and || have the advantage that you just need to think about the truth table and you remember what they are supposed to be doing. Also anecdotal but not having English as my first language I do have much more love for symbols than words in English, which will are often already sufficiently overloaded just for someone trying to learn English.

Because it is not an work-reducing optimization.

10 Likes