0

How can the C compiler understand isOn as false if the return value of the variable is 0?

enum bool { false, true };

typedef enum bool boolean;

int main()
{
    boolean isOn = false;
    printf("%d\n", isOn);
    if(!isOn)
        printf("IS FALSE");
    return 0;
}

Do C understand 0 as null and all other numbers as non-null?

  • `0` evaluates to false. All others evaluate to true. – Reticulated Spline Sep 24 '18 at 20:10
  • 4
    Don't use homebrew boolean type, use `bool` from `stdbool.h` – Eugene Sh. Sep 24 '18 at 20:11
  • What do you mean with null and non-null? `false` and `true` or `null` as in `null` pointer? The former has nothing to do with the latter. – Bruno Cadonna Sep 24 '18 at 20:39
  • Long time a go someone have said to me 0 in C is considered `null` and `null` could be considered `false` in some occasions. – Rodrigo Xavier Sep 24 '18 at 20:45
  • @RodrigoXavier -- the null pointer macro in C is `NULL` , not `null`. There are null pointers, and `NULL`: with `int *x = NULL;` you have `x`, a null pointer which is guaranteed to compare equal to the null pointer macro `NULL`. It is true that null pointers evaluate to false in conditional expressions; `NULL` is typically (always?) defined as `(void *) 0`, i.e., the integer constant `0` cast to a `void` pointer. – ad absurdum Sep 24 '18 at 21:11
  • See this question for further information on null-pointer and NULL: https://stackoverflow.com/questions/9894013/is-null-always-zero-in-c – Bruno Cadonna Sep 24 '18 at 21:44

2 Answers2

1

In C the integer value 0 is considered false when used in a boolean context, while any non-zero value is considered true in a boolean context.

The values of an enum start at 0 and increase if not specifically set, so for the enum you've created, false has a value of 0 while true has a value of 1.

In the statement if (!isOn), the ! operator changes the boolean value of the given expression, with !0 being 1 and any other value given being 0. Since isOn has the value 0, !isOn has the value 1, so the if statement is true and "IS FALSE" is printed.

dbush
  • 205,898
  • 23
  • 218
  • 273
-1

By default, C compiler has no bool type (and true/false definitions). bool type is implemented in system header stdbool.h, you should include it at first.

As I know, gcc compiler implements true and false as 0 and 1 defines, Microsoft MSVC (Microsoft Visual Studio) as 0 and 204.

And yes, 0 in C is false and other value is true

AJIOB
  • 329
  • 5
  • 12