×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Use of bool in C language

C | bool data type with examples: In this tutorial, we are going to learn about the bool data type in C programming language with its usages, syntax and examples.
Submitted by IncludeHelp, on June 06, 2020

First, understand the bool in C++ programming language. In C++ programming, "bool" is a primitive data type and it can be used directly like other data types. "bool" is a Boolean data type that is used to store two values either true (1) or false (0).

bool type in C

But in C programming language, a "bool" is defined in stdbool.h header file. Thus, to use a bool type in our program, we must include stdbool.h header files. As a standard feature, a bool variable can store either true (1) or false (0) value.

Syntax:

bool variable_name;

Example 1

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

int main()
{
    bool var1 = true;
    bool var2 = false;
    bool var3 = 1;
    bool var4 = 0;

    // printing the values
    printf("var1: %d\n", var1);
    printf("var2: %d\n", var2);
    printf("var3: %d\n", var3);
    printf("var4: %d\n", var4);

    return 0;
}

Output:

var1: 1
var2: 0
var3: 1
var4: 0

Example 2

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

int main()
{

    bool status = true;

    if (status)
        printf("It's true...\n");
    else
        printf("It's false...\n");

    status = false;

    if (status)
        printf("It's true...\n");
    else
        printf("It's false...\n");

    return 0;
}

Output:

It's true...
It's false...

Note: Any non-zero value will be considered as a true value. Thus, we can assign anything that should return either non-zero or zero.

Consider the below example,

Example 3

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

int main()
{
    bool x = true;

    printf("x : %d\n", x);

    x = -1;
    printf("x : %d\n", x);

    x = -123.45f;
    printf("x : %d\n", x);

    x = "Hello";
    printf("x : %d\n", x);

    x = 123.456f;
    printf("x : %d\n", x);

    x = 0;
    printf("x : %d\n", x);

    x = NULL;
    printf("x : %d\n", x);

    return 0;
}

Output:

x : 1
x : 1
x : 1
x : 1
x : 1
x : 0
x : 0

Also read: bool data type in C++




Comments and Discussions!

Load comments ↻





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