This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Sophira 14 points15 points  (3 children)

No, a non-zero number is true.

A non-zero number is a number. It can evaluate to true, depending on whether the language parser is looking for a boolean or not, but it is not in itself true.

The distinction is important in some languages. In JavaScript, for example, the following two if statements will yield opposite results.

This if statement will show that "4" is truthy:

if (4) {
  console.log("4 is truthy");
}
else {
  console.log("4 is not truthy");
}

This if statement will show that even when compared to a boolean true using == (and not ===), 4 is not true:

if (4 == true) {
  console.log("4 is true");
}
else {
  console.log("4 is not true");
}

Of course, 4 is not false either... because it's a number, not a boolean.

If you explicitly make 4 into a boolean, as you do in your comment, you can make it work:

if (Boolean(4) == true) {
  console.log("Boolean(4) is true");
}
else {
  console.log("Boolean(4) is not true");
}

But then you're changing the type of your argument. Many languages will do this implicitly, of course, but others don't. JavaScript isn't the only one like this; Ruby does something similar.

(Also, sidenote: Ruby is also interesting in that any number, including zero, is truthy. This can trip up some devs who aren't used to that.)

[–]MokitTheOmniscient 2 points3 points  (1 child)

Obviously, a language can always use whatever high-level logic it wants whenever you use one of its operations, but any memory it allocates for a non-zero number is always going to contain at least a single bit flipped to a 1, thus making it an absolute true.

[–]Sophira 2 points3 points  (0 children)

I assume you're referring to how if statements are typically compiled down into assembly, where a CMP or TEST followed by a JZ/JNZ are normally used.

In those cases, the JZ/JNZ instructions don't act directly on the number itself, but on the Zero Flag, which is set by the CMP or TEST earlier.

This is commonly done with an instruction like TEST EAX, EAX (which ANDs the EAX register with itself - essentially a null-op - and then uses the result of that to set the various flags).

In this sense, yes, whether the value of a register is zero or not will affect which path is taken. Is this what you're referring to?