printf() format specifier for bool

Learn about the bool type in C, and its format specifier with printf().
Submitted by Shubh Pachori, on July 10, 2022

In C programming language, bool is a Boolean Datatype. It contains only two types of values, i.e; 0 and 1. The Boolean Datatype represents two types of output either it is true or it is false. In this 0 represents the false value and 1 represents the true value. In C programming language we have to use the stdbool.h header file for implementation of the Boolean Datatype. In Boolean, Datatype 0 is stored as 0 but all other positive values other than 0 are stored as 1.

Example 1: C language code for understanding the use of Boolean Datatype (bool)

#include <stdio.h>
#include <stdbool.h> // Boolean Header file

int main()
{
    // declaring a Boolean variable
    bool b = true; 

    if (b == true) {
        printf("True");
    }
    else {
        printf("False");
    }
    
    return 0;
}

Output:

True

In C, there is no format specifier for Boolean datatype (bool). We can print its values by using some of the existing format specifiers for printing like %d, %i, %s, etc.

Example 2: Printing bool values using %d format specifier

#include <stdio.h>
#include <stdbool.h>

int main()
{
    bool b1 = true;
    bool b2 = false;
    
    //using %d as a format specifier of bool
    printf("For true:%d\n", b1); 
    printf("For false:%d\n", b2);
    
    return 0;
}

Output:

For true:1
For false:0

In the above output, we can see that there is returned value 0 for false and 1 for true Boolean values by the %d format specifier for Boolean Datatypes.

Example 3: Printing bool values using %i format specifier

#include <stdio.h>
#include <stdbool.h>

int main()
{
    bool b1 = true;
    bool b2 = false;
    
    //using %i as a format specifier of bool
    printf("For true: %i\n", b1); 
    printf("For false: %i\n", b2);
    
    return 0;
}

Output:

For true: 1
For false: 0

Example 4: Printing bool values using %s format specifier

#include <stdio.h>
#include <stdbool.h>

int main()
{
    bool b1 = true;
    bool b2 = false;
    
    // using %s as a format specifier of bool
    printf("%s\n", b1 ? "true" : "false"); 
    printf("%s\n", b2 ? "true" : "false");
    
    return 0;
}

Output:

true
false



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.