top

Search

C Tutorial

.

UpGrad

C Tutorial

Boolean in C

Overview

The Boolean data type is introduced in the C programming language through the stdbool.h library, is a fundamental aspect that plays a vital role in various operations such as condition checking, decision making, and more. In this article, we delve deep into Boolean in C, explore its usage, syntax, and operations, and illustrate with practical examples. 

Let's begin this journey to learn how to print Boolean in C and its various implementations. 

Definition of Boolean in C Programming Language

In C, a Boolean is not a built-in data type. However, in 1999, with the C99 standard, the Boolean data type was introduced via the stdbool.h library. This allows the use of the bool keyword to declare Boolean variables.

#include <stdbool.h>
int main() {
    bool b = true;
    return 0;
}

In the above code, we have imported the stdbool.h library and declared a Boolean variable 'b' with the value 'true', while there is no format specifier for Boolean in C. This is an elementary example of how you can use Boolean in C.

Why Do We Need Boolean Values?

Boolean values are crucial in programming languages, not just in C but across the board. Boolean values essentially have two states - true or false, and these states play a vital role in controlling the flow of programs. Here's why Boolean values are indispensable in programming:

1. Decision Making: In programming, decisions are made using conditional statements like if, else, switch, etc. These conditional statements evaluate expressions that return a Boolean value. The program decides the next course of action based on whether the result is true or false.

#include <stdbool.h>

int main() {
    bool isRaining = true;
    if(isRaining) {
        printf("Take an umbrella!");
    } else {
        printf("Enjoy the sun!");
    }
    return 0;
}

In the above example, if isRaining is true, the program prints "Take an umbrella!". If isRaining is false, it prints "Enjoy the sun!".

2. Loop Control: Boolean values are instrumental in controlling loops. A loop continues to execute as long as a particular condition evaluates to true. Once the condition becomes false, the loop stops.

#include <stdbool.h>

int main() {
    bool keepRunning = true;
    int count = 0;
    while(keepRunning) {
        printf("Loop iteration: %d\n", count);
        count++;
        if(count > 5) {
            keepRunning = false;
        }
    }
    return 0;
}

In the above example, the while loop keeps running as long as keepRunning is true. Once the count exceeds 5, keepRunning is set to false, and the loop stops.

3. Simplicity and Readability: Boolean values simplify and make the code more readable. Since Boolean expressions return either true or false, they make the code easier to understand and debug.

#include <stdbool.h>

bool isEven(int num) {
    return num % 2 == 0;
}

int main() {
    int num = 4;
    if(isEven(num)) {
        printf("%d is even.", num);
    } else {
        printf("%d is odd.", num);
    }
    return 0;
}

In the above example, the isEven function makes the code more readable and easier to understand.

4. Error Checking: Boolean values are commonly used in error checking. Many functions return a Boolean value to indicate whether they succeeded (true) or failed (false).

#include <stdbool.h>

bool divide(int a, int b, float *result) {
    if(b == 0) {
        return false;
    }
    *result = (float) a / b;
    return true;
}

int main() {
    float result;
    if(divide(10, 2, &result)) {
        printf("Result is: %.2f", result);
    } else {
        printf("Error: Division by zero");
    }
    return 0;
}

In this example, the divide function returns false if we try to divide by zero, an illegal operation in mathematics.

In essence, Boolean values are a necessity in programming due to their role in decision-making, loop control, code simplicity, and error checking. They form the basis of many fundamental aspects of programming logic.

Boolean Data Type in C

The Boolean data type is a basic data type in most high-level programming languages, but it was not part of the original C language specification. It was later included in the C99 standard via the stdbool.h library.

Definition of Boolean Data Type

In C programming, the Boolean data type is denoted by the keyword 'bool'. A variable of the type 'bool' can hold one of two values: 'true' or 'false'. These are predefined in the stdbool.h library. Under the hood, 'true' is equivalent to the integer value 1, and 'false' is equivalent to 0.

Here's a simple example of declaring and initializing Boolean variables:

#include <stdbool.h>

int main() {
    bool isTrue = true;
    bool isFalse = false;

    return 0;
}

In this example, we have two Boolean variables: 'isTrue' and 'isFalse'. The first is set to 'true', and the second is set to 'false'.

Size and Range of Boolean Data Type

The size of the Boolean data type in C (i.e., 'bool') is 1 byte. That's because it only needs to represent two values: 'true' (1) or 'false' (0). The range of values that can be represented is hence 0 to 1.

Syntax for Defining Boolean Variables

The syntax for defining Boolean variables in C is straightforward. First, you must include the stdbool.h library at the beginning of your program. Then, you can use the 'bool' keyword to declare Boolean variables.

Here is an example:

#include <stdbool.h>

int main() {
    bool isCodingFun = true;
    bool isEarthFlat = false;

    return 0;
}

In this code snippet, we declare two Boolean variables: 'isCodingFun' and 'isEarthFlat'. The first is set to 'true', indicating that we believe coding is fun. The second is set to 'false', reflecting the widely accepted fact that Earth is not flat.

This flexibility in defining meaningful variable names and assigning them logical Boolean values can make your code more readable and understandable.

Using Boolean data types in C can improve your code's clarity and efficiency, especially when working with conditional statements, loops, and functions that return a true or false value. Despite their simplicity, they are powerful tools in a programmer's toolkit.

Boolean Arrays in C

In C, you can create arrays of Boolean values to store multiple Boolean variables in a contiguous block of memory. Boolean arrays are useful when working with a collection of true/false values. Here is an example:

#include <stdbool.h>
int main() {
    bool arr[3] = {true, false, true};
    return 0;
}

In the above code, we have declared an array of Boolean type with three elements.

Boolean Logical Operators in C Language

Logical AND Operator

The Logical AND operator (&&) returns true if both operands are true; otherwise, it returns false.

#include <stdbool.h>
int main() {
    bool a = true, b = false;
    bool result = a && b;
    printf("Result of a && b: %d\n", result);
    return 0;
}

In this example, the variable 'result' will be false because one of the operands 'b' is false.

Logical OR Operator

The Logical OR operator (||) returns true if either (or both) of the operands is true.

#include <stdbool.h>
int main() {
    bool a = true, b = false;
    bool result = a || b;
    printf("Result of a || b: %d\n", result);
    return 0;
}

Here, 'result' will be true as one of the operands 'a' is true.

Logical NOT Operator

The Logical NOT operator (!) returns the inverse of the operand's value.

#include <stdbool.h>
int main() {
    bool a = true;
    bool result = !a;
    printf("Result of !a: %d\n", result);


    return 0;
}

In this case, 'result' will be false because we are inverting the value of 'a', which is true.

Comparison Operators in C

Comparison operators, like Boolean logical operators, are used to compare values in C programming. They return a Boolean value, either true (if the comparison is correct) or false (if the comparison is incorrect). Let's look at these operators in detail.

Equal to (==) Operator

The equal to the operator (==) checks if both operands are equal.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a == b);
    return 0;
}

In this case, 'result' will be false because 'a' is not equal to 'b'.

Not Equal to (!=) Operator

The not equal to operator (!=) checks if the operands are not equal.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a != b);
    return 0;
}

Here, 'result' will be true as 'a' is not equal to 'b'.

If you’re wondering how to compare boolean in C, these two mentioned operands above are the right choice. 

Greater Than (>) Operator

The greater than operator (>) compares the values of the left and right operands, determining if the value of the left operand is greater than the value of the right operand. If the condition is true, it evaluates to true; otherwise, it evaluates to false.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a > b);
    return 0;
}

In this example, 'result' will be false because 'a' is not greater than 'b'.

Less Than (<) Operator

The less than operator (<) checks if the value of the left operand is less than the value of the right operand. If the condition is true, it returns true; otherwise, it returns false.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a < b);
    return 0;
}

In this case, 'result' will be true because 'a' is less than 'b'.

Greater Than or Equal To (>=) Operator

The greater than or equal to the operator (>=) checks if the value of the left operand is greater than or equal to the value of the right operand. If the condition is true, it returns true; otherwise, it returns false.

#include <stdbool.h>
int main() {
    int a = 20, b = 20;
    bool result = (a >= b);
    return 0;
}

Here, 'result' will be true because 'a' is equal to 'b'.

Less Than or Equal To (<=) Operator

The less than or equal to operator (<=) checks if the value of the left operand is less than or equal to the value of the right operand. If the condition is true, it returns true; otherwise, it returns false.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a <= b);
    return 0;
}

In this example, 'result' will be true because 'a' is less than 'b'.

These comparison operators are fundamental to constructing logical statements in C and controlling the flow of a program. They allow the program to make decisions and perform different operations based on various conditions.

Boolean Expressions in C

A Boolean expression in C is a valid expression that results in a Boolean value, either true or false. These expressions are frequently used in conditional statements and loops.

#include <stdbool.h>
int main() {
    int a = 10, b = 20;
    bool result = (a > b);
    return 0;
}

Here, 'result' will be false as 'a' is not greater than 'b'.

Conclusion

Bool in C library was introduced with the C99 standard via the stdbool.h library. It enables the declaration of variables that can store true or false values, providing the necessary definitions and constants for Boolean operations in C.

Boolean values are crucial in programming for decision-making, loop control, and logical operations. They simplify code, enhance readability, and improve program logic. Knowing how to leverage this can further assist you in simplifying your programming skills. This is where upskilling plays its role!

The Master of Science in Computer Science offered by upGrad, in collaboration with Liverpool John Moores University, is designed to propel your career and ensure you stay abreast of the latest trends in the dynamic tech industry.

FAQs

1. Is there a Boolean data type in C?

Before the C99 standard, there was no built-in Boolean data type in C. However, the C99 standard introduced a bool data type through the stdbool.h library. 

2. How to declare a Boolean variable in C?

To declare a Boolean variable in C, first, include the stdbool.h library. Then use the bool keyword to declare your Boolean variable. For example:

#include <stdbool.h>
bool variable_name = true; // or false

3. What is the size of the Boolean data type in C?

In C, the size of a Boolean data type (bool) is 1 byte. It can hold one of two values: 0 (false) or 1 (true).

Leave a Reply

Your email address will not be published. Required fields are marked *