How to print a boolean value in C language? Code Example

Total
0
Shares

There is no format specifier for Boolean in C language. But we can print True/False using conditional operators.

Suppose you have a boolean –

bool abc = true;
bool def = false;

Now in order to print true for abc using printf, we don’t have any format specifier like int (%d) or string (%s).

bool abc = true;
bool def = false;

printf(abc ? "true" : "false");
// Output 👉 true

printf(def ? "true" : "false")
// Output 👉 false

We need to use format specifier of string along with ternary conditional. Like this –

bool abc = true;
bool def = false;

printf("Value of abc is %s", abc ? "true" : "false");
// Output 👉 Value of abc is true

printf("Value of def is %s", def ? "true" : "false")
// Output 👉 Value of def is false

We can also use fputs() function –

bool abc = true;
bool def = false;

fputs(abc ? "TRUE" : "FALSE", stdout);
// Output 👉 TRUE

fputs(def ? "TRUE" : "FALSE", stdout);
// Output 👉 FALSE