6

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?

sheepez
  • 986
  • 1
  • 10
  • 26
Spasiu
  • 185
  • 2
  • 9

3 Answers3

20

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

AshleyF
  • 3,682
  • 1
  • 25
  • 23
  • 3
    This is the actual, correct answer to the OP's question. It also allows the host CPU to make branch-free decisions using AND and OR instead of multiplication and addition. E.g., P1 A1 AND P2 A2 AND OR, if Px are predicates and Ax are the corresponding answers, versus its equivalent in C, A1*P1 + A2*P2. Other languages also used -1 for true (BASIC, PL/I, etc.), so C was in the minority at the time. Think of it as a "signed boolean." – Samuel A. Falvo II Dec 15 '14 at 00:46
5

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • http://stackoverflow.com/questions/23838410/interrupts-instruction-pointer-and-instruction-queue-in-8086 – Patt Mehta May 24 '14 at 04:03
  • I read that bit from the documentation about flags before I came to stack overflow, but I was missing the bit about two's complement. So 11111111 comes out as -1 in 2's complement. Every machine that I've used Forth with has returned -1, but you're saying it's conceivable that some computer out there is going to return 255? What kind of computer wouldn't use two's compliment under these circumstances? – Spasiu May 25 '14 at 03:22
  • Apparently Unisys still sells 36-bit word, 1's complement UNIVAC mainframes but I can't find anything else that isn't now 2's complement. – Tommy May 25 '14 at 04:34
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Recifarium
  • 21
  • 2