0

In my current class I am seeing a lot of times where my teacher puts a number as the condition of an if statement then asks for the output. I'm confused as to how these statements are being evaluated. Example:

if(-1) {
   x = 35;
}

or

if(0) {
   x = 35;
}

Why does it go inside the if statement instead of just ignoring it? What is making if(-1) evaluate true? And why does if(0) evaluate false?

This is an online class so I can't get help directly from the teacher usually. I have searched for a few hours on various websites about C for loops, but I haven't found anything relevant yet to my question.

Zachary
  • 87
  • 1
  • 13
  • 4
    `0` stands for *false*, all other integers (e.g. `-1`) values stand for *true* – Dmitry Bychenko Sep 09 '20 at 20:05
  • The question is different but the answer does seem to answer my question. Any non-zero number evaluates true in C, is that correct? @mkrieger1 – Zachary Sep 09 '20 at 20:06
  • As to "why does it do inside ... instead of just ignoring it?". Purely for educational purposes. The compiler will almost treat `if(-1) { x = 35; }` exactly the same as `x = 35`, and will completely remove `if(0) { x = 35; }`. – William Pursell Sep 09 '20 at 20:07
  • 1
    Interesting tidbit: the expression `a > b` has a value of type `int`. That value is either `0` or `1` ... so `if (a > b)` is ultimately executed as either `if (0)` or `if (1)` – pmg Sep 09 '20 at 20:08
  • @pmg It looks like the only operator that will result in `bool` type is the cast `(bool)` :) – Eugene Sh. Sep 09 '20 at 20:50

1 Answers1

3

C doesn't have a "real" boolean type. When evaluating integers, 0 is a "false", and anything else is a "true" value.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Well, I find this statement somewhat misleading. C does have a "real" `bool` type, and it can be proven: https://ideone.com/t6RTk0 – Eugene Sh. Sep 09 '20 at 20:39