w3resource

Print the result of a boolean as 'false' or 'true' in C language

How do you print a boolean in C?

There is no format specified for bool types.

C does not have boolean data types, and normally uses integers for boolean testing.

  • One is used to represent true and Zero is used to represent false.
  • For interpretation, anything non-zero is interpreted as true and Zero is interpreted as false.

Example: print a boolean in C

#include <stdio.h>

int main()
{
bool flag = true;
printf("%d", flag); // prints 1
printf("\n");
printf(flag ? "true" : "false"); // prints true
printf("\n");
printf("%s", flag ? "true" : "false"); // prints true
printf("\n");
fputs(flag ? "true" : "false", stdout); // prints true
}

To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

#define was used in the old days to accomplish this:

  • #define true 1
  • #define false 0

Currently, it is better to use const int instead of #define:

  • const int true = 1;
  • const int false = 0;

In C99, a new header, stdbool.h, defines the following types and constants:

The type "bool" is the same as a newly defined type "_Bool"

  • _Bool is an unsigned integer, that can only be assigned the values 0 or 1
  • Attempting to store anything else in a _Bool stores a 1.
  • Variables can now be declared of type "bool".

stdbool.h also defines constants "true" and "false", with value 1 and 0 respectively.

To use these new features, use #include <stdbool.h> at the top of your program.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/c-snippets/print-the-result-of-a-bool-as-false-or-true-in-c.php