5
votes

The Forth code

7 3 > . (7 > 3)

returns -1, but every other language I've ever used uses 1 as a flag for true. Why is this? What accounts for this difference?

3
My guess is that it's a wish to have TRUE be the bitwise inversion of FALSE.Veedrac
C uses non-zero as true, not 1. Never used it?user207421
@EJP C's tests accept non-zero as true. So do Forth's tests. C's canonically true value, as returned by comparison operators, is 1. Forth's is -1.Julian Fondren

3 Answers

19
votes

-1 is all bits set which then has the benefit that words such as and, or, not, ... serve as both logical and bitwise operators (as opposed to say C with &&, ||, !, ... vs. &, |, ~, ...)

5
votes

Per the 1994 standard:

Flags Flags may have one of two logical states, true or false. Programs that use flags as arithmetic operands have an environmental dependency. A true flag returned by a standard word shall be a single-cell value with all bits set. A false flag returned by a standard word shall be a single-cell value with all bits clear.

So true is not -1, it's all bits set — the logical opposite of no bits set. In your particular environment, all bits set is -1, presumably because your computer uses two's complement arithmetic. But it doesn't have to in order to run Forth and therefore true doesn't have to be -1.

0
votes

It is because all processors have a branch-if-zero instruction and not branch if all one's.

So if you want a construct like this:

test IF (some code) ELSE (other code) THEN 

you are going to use a branch to reach the (other code) part. This branch will be a branch if zero so this implies that 0 is a false flag and the contrary will be

0 NOT 

which is all one's so it means true.