Spasiu
Spasiu

Reputation: 185

Why does Forth return -1 as a flag for True?

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?

Upvotes: 6

Views: 1344

Answers (3)

Recifarium
Recifarium

Reputation: 21

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.

Upvotes: 0

AshleyF
AshleyF

Reputation: 3752

-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. &, |, ~, ...)

Upvotes: 20

Tommy
Tommy

Reputation: 100632

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.

Upvotes: 6

Related Questions