C language truth value

This is an explanation of the truth value of C language.

C language truth value

In C, 0 is a false value and everything else is a true value. It's very simple. NULL is a false value because it is defined as equivalent to 0 in C.

True value Non-zero
False value 0

Let's use the true and false value in the if statement.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  int32_t flag = 1;
  // int32_t flag = 0;
  
  if (flag) {
    printf("OK\n");
  }
  else {
    printf("Not OK\n");
  }
}

When the flag is 1, "OK" is displayed, and when the flag is 0, "Not OK" is displayed.

Let's also use NULL.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  const char * string = "Hello";
  // const char * string = NULL;
  
  if (string) {
    printf("OK\n");
  }
  else {
    printf("Not OK\n");
  }
}

"OK" is displayed when a character string is assigned, and "Not OK" is displayed when NULL is assigned.

Is there a false value type in C?

C99 introduced stdbool.h and added the _Bool type.

It is a type that can only be 1 or 0.

However, it is unlikely that the processing system will be implemented with 1 bit, and at least 1 byte is used, so I think that int8_t that can be used for general purposes may be sufficient. ..

I usually use int32_t, and if I want to save size, it's like int8_t.

I will leave it to you to decide whether to use it. My evaluation is that it's okay, but it doesn't have to be.

What is the difference from Perl's boolean value?

The C Boolean value is similar to Perl Boolean.

In C, 0 is a false value and everything else is true. NULL is false because it is defined as equivalent to 0.

In Perl, the number 0, the string 0, undef, the empty string, and the empty list are false values, otherwise true.

As for the true and false value, Perl and C language can be used in a similar way.

Associated Information