Question

I guess this is trivial for most of good1 programmers, but I'm so used to programming using true and false2 that when I encounter 0 and 1, I can never remember which one means true and which one means false.

Any suggestions?

1Good: I mean one who knows C, of course :)
2I am a Java developer, as you have guessed ;)

Was it helpful?

Solution

Haven't you ever noticed that everyday items' power switches use a circle for off, and a line for on?

It's not much of a jump to link them up.

Off = circle = zero = false

On = line = one = true

OTHER TIPS

The mnemonic is "how much truth is in this?" Zero integer means zero truth. Anything else is nonzero truth. :)

I have a co-worker who simply has a Post-It note on his wall beside his desk:

False = 0
True != 0

If you are really having that much trouble with it, I would use the language to abstract it away.

e.g. in C

#define TRUE 1
#define FALSE 0

In general I would avoid having constants lying around in code anyways.

Consider,

if(my_var == TRUE)

as opposed to,

if(my_var == 1)

Though, here again you need to make sure you are testing for the right thing,

if(my_var != FALSE)

will catch more cases.

Cheers!

Christian

"Oh No!"
(Oh == 0)

This is complicated by the fact that in the shell (sh, bash) true is 0 and false is 1:

$ true
$ echo $?
0
$ false
$ echo $?
1

Remember "nothing == false", "something == true"

No mnemonic - and it gets even more complex if you come from a hardware background. But for programmers, just ask the question:

Is any bit set?

The answer is either true or false, and is the result. Only 0 (even in signed integers) has no bits set.

-Adam

Map both to On and Off. I think most programmers would map both sets the same way: 1/true both going to 'On', while 0/false both go to 'Off'.

It depends on the language.

  • C: ( 0 ? "never happens" : "false") and ( 1 ? "true" : "never happens")

  • Ruby, ELisp: both 0 and 1 are true

  • bash (or cmd.exe): the true command (from coreutils) exits with a 0 status code and the false command exits with a non-zero status code

Many modern popular programming languages have strong C heritage therefore they consider 0 to be false and 1 (or any non-zero numbers) to be true.

Don't use mnemonics for boolean, use your language's idioms to test trueness.

love c - because you can't multiply lies. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top