1

I am having trouble understanding why the following code:

0 || -1

Evaluates to 1? More specifically, I am confused as to what the || and && operators mean when applied to integers.

Adam Lee
  • 436
  • 1
  • 14
  • 49
  • because any non-zero is `true` – Eugene Sh. Dec 10 '19 at 23:00
  • Possible duplicate of [How || and && works](https://stackoverflow.com/questions/17348622/how-and-works) – GSerg Dec 10 '19 at 23:03
  • 1
    Relevant: the spec links in kennytm’s answer to https://stackoverflow.com/questions/37291681/does-the-c-standard-explicitly-indicate-truth-value-as-0-or-1 – Ry- Dec 10 '19 at 23:03
  • `||` will give `0` if both operands equal `0` ; otherwise will give `1`. – M.M Dec 10 '19 at 23:05

1 Answers1

2

Every expression value != 0 evaluates to 1, if value is not equal to zero. (see comment from @MiCo and @M.M.)

|| is an or operation with two operands. If the left or the right operand is not zero the or operation evaluates to 1.

Since -1 is not 0 it evaluates to 1,

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
  • Since there is actually no true value in C, I would better say that every value !=0 evaluates to 1. – MiCo Dec 10 '19 at 23:06
  • @MiCo Well that is not true either. `3` for example doesn't evaluate to `1` . (nor does it evaluate to `true`), it evaluates to `3` – M.M Dec 10 '19 at 23:08
  • OK, you are right. To be more precise I meant it like this: every expression (value!=0) evaluates to 1, if value is not zero, for example (3 != 0) evaluates to 1. – MiCo Dec 10 '19 at 23:16
  • @MiCo C has had `_Bool` for 20 years. Yes C has a _true_ value. – chux - Reinstate Monica Dec 11 '19 at 03:23