Boolean in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

Boolean logic, with its fundamental concepts of true and false, underpins the very core of computing and programming. In this article, we delve into the significance of Boolean in the context of one of the most widely used programming languages, C. Computers, inherently binary devices, primarily operate on these binary states, and understanding Boolean logic is pivotal for making decisions and controlling program flow. We explore the Boolean data type in C, its syntax, implementation, and practical usage, shedding light on how it influences conditional statements, loops, and function return types. Join us on this journey through the world of Boolean in C.

Boolean

Since the computers operate on 0’s(False) and 1’s(True) computer logic is also expressed in boolean terms and all the complex logic of computers and digital systems is evaluated by using boolean algebra to take the particular decisions. So through this article, we will discuss the significance of Boolean in C in context with one of the most popular computer languages C.

Computers and other Digital Systems only think in terms of ON(True) or OFF(False), whereas we humans use a very diverse set of symbols in our daily life apart from these two terms. But when there comes a situation to make a decision, we only think in terms of Yes(True) or No(False) statements, which is nothing but a Boolean. Yes, you heard right, it’s Boolean. Boolean in C or boolean logic is a subset of algebra used for creating True or False statements. The term Boolean Algebra is named after the great mathematician George Boole. Hence, any kind of logic, expressions, or work theories by George Boole is considered Boolean.

Boolean in C

Boolean Variables

In C the terminology of boolean is associated with data type and Boolean is termed as one of the data types in the C Standard Library. This data type stores one of the two possible values denoted by true or false, which represents two truth values of logic and Boolean Algebra. All non-zero values are treated as true, while 0 is treated as false.

Though the boolean data type in C only stores true or false values, they are really very important in programming because they allow us to control the flow of code in different situations. The Boolean data type in C can be invoked after including the "stdbool.h" header file. It means the C program will give a compilation error if we directly try to use boolean data type in C without including the stdbool.h header, whereas in C++, we do not have to include any extra headers.

Boolean Variable in C

Syntax

To declare a boolean data type in C, we have to use a keyword named bool followed by a variable name.

Here, bool is the keyword denoting the boolean data type in C and var_name is the variable name.

A bool takes in real 1 bit, as we need only 2 different values(0 or 1). So the sizeof(var_name) will give the result as 1 i.e. 1byte is required to store a boolean value and other 7 bits will be stuffed with 0 values.

Implementation of Boolean in C

Using header file stdbool.h

In the above example, we have included the stdbool.h header file as we are using the bool type variable in our program, then we have declared a variable x of type boolean using bool and initialized it with value false. After that, we applied the condition checks using the if-else block to determine if the value of variable x is true or false.

What if we forgot the name of the header file to include for using boolean data type or what if we don’t want to include any extra header in our program but want to use boolean data type?

Well, we know that C doesn’t provide us with a boolean as a predefined data type. In such a scenario, we will have to create our custom data type, which will behave the same as shown in the previous example. To do this we can leverage the power of keyword typedef and enumeration (enum) in C.

Let’s understand this with an example.

Using the Enumeration Type & typedef

Isn’t it simple? Let’s try to understand what we have implemented in the above example.

enum (enumeration) is a user-defined data type in C used to assign names to integer constants. In our case, we have assigned false to constant 0 state and true to constant 1 state using enum.

The typedef keyword is used to give a symbolic name to the type and is automatically interpreted by the compiler. In our case, we have assigned it as a bool_enum.

Hence, now we can use this custom type bool_enum which will behave the same as that of the boolean data type from the stdbool.h header file.

Using #define to Declare Boolean Values:

You can use preprocessor macros to define Boolean values:

Comparing Values and Variables

In C, you can compare values and variables using Boolean expressions, which evaluate to either true (1) or false (0). Here's a explanation with examples:

Comparison Operators: Use comparison operators to compare values.

Example:

Equality Operators: Use equality operators (== and !=) to check for equality or inequality.

Example:

Conditional Ternary Operator: The ternary operator (?) can be used for concise conditional checks.

Example:

These examples demonstrate how to use Boolean expressions to compare values and variables in C, resulting in true (1) or false (0) outcomes.

Boolean Arrays in C:

Like normal arrays, we can also create the boolean arrays using the data type bool from stdbool.h header file in C. The boolean array can store multiple true or false values for each element and all elements and can be accessed by using indexes.

Let’s see a small example to declare, initialize and print all elements from a boolean array. Through this example, we will try to initialize true value to all even indexed elements and false to all odd indexed elements.

In the above example, we have declared the boolean array and initialized all even index elements with true values and odd index elements with false values. Then we tried accessing those values based on indexes and tried printing them to the console.

Boolean with logical operators

We have already seen that Operators need some boolean conditions or boolean results to act upon. So for more clarity, we will assume set A and set B represent two independent boolean conditions or boolean results, and we will use them to understand the behavior of the boolean operators.

Types of logical operators in the C

1. && (AND) Operator in C: The && (AND) operator is C also known as logical conjunction and requires both left-side expression and right-side expression to be true for the result to be true. All other cases results are false. This is logically the same as the intersection of two sets.

And Operator in C

The truth table for the && (AND) Operator is given below,

Truth Table for AND Operator in C

Where A denotes the expression on the left side of the operator and B denotes the expression on the right side of the operator.

  1. || (OR) Operator in C: The || (OR) operator in C requires only one of the boolean logic to be true for the result to be true. This is equivalent to the union of two sets.

OR Operator in C

The truth table for the || (AND) Operator is given below,

Truth Table for OR Operator

Where A denotes the expression on the left side of the operator and B denotes the expression on the right side of the operator.

Short-Circuiting:

There is a concept that is closely associated with the && (AND) and || (OR) operators named Short-Circuiting. It is a compiler optimization technique to avoid evaluating an unnecessary expression. As expressions are evaluated from left to right, there are some expressions that are calculated certainly by only evaluating parts of the expression. This technique detects such expressions and helps the compiler to achieve possible optimization.

For Example: In C++, there are possibilities of short-circuiting at a time of evaluating && (AND) and || (OR) operators. At the time of evaluating && (AND) operator if the expression on the left-hand side of the operator gives a false result, then irrespective of the values of the right-hand side the boolean expression will always give a false as the final result. So, in this situation evaluation of the right-hand side is avoided by the compiler.

Similarly, in the case of the || (OR) operator when the left hand evaluates to true, the result of the expression will always be true irrespective of the value of the right-hand side of the operator.

3. ! (NOT) Operator: The ! (NOT) Operator in C is used to negate the boolean value used after it. It only requires a single boolean value as an expression.

Example:

The truth table for the || (AND) Operator is given below,

Truth Table for NOT Operator

Now let’s try to use these logical operators with booleans in C using a simple example.Now let’s try to use these logical operators with booleans in C using a simple example.

In the above example, we have seen how various boolean operators like AND, OR, and NOT evaluate the boolean values.

Using bool in Loops

You can use bool values to control loops, typically in conditions like while or for. Here's an example of boolean in C, using a bool variable in a while loop:

In this example, the continueLoop variable of type bool is used to control the while loop. The loop continues as long as continueLoop is true.

Using bool as a Function Return Type

You can define functions with a bool return type to indicate success or failure. Common practice is to use true for success and false for failure. Here's an example:

In this example, the isEven function returns true if the input number is even and false otherwise. The function's return type is bool.

Using bool in loops and as a return type allows you to write more expressive and readable code, especially when dealing with conditions and function outcomes that involve true/false logic.

Conclusion

  1. Boolean or boolean logic is a subset of algebra used for creating True or False statements all the complex logic of computers and digital systems is evaluated by using boolean algebra to take particular decisions.
  2. In C the terminology of boolean is associated with data type and Boolean data type in C is termed as one of the data types in the C Standard Library and can be invoked after including the stdbool.h header file.
  3. We can create a custom type bool by leveraging the power of keyword typedef and enumeration (enum) in C.
  4. We can also create the boolean arrays using the data type bool from the stdbool.h header file in C. The boolean array can be used to store multiple true or false values for each of its elements.
  5. There are three types of logical operators in the C language: && (AND) operator, || (OR) operator, !(NOT) operator.
  6. The && (AND) operator is C requires both left side expression and right side expression to be true for the result to be true.
  7. The || (OR) operator in C requires only one of the boolean logic to be true for the result to be true
  8. The ! (NOT) Operator is used to negate the value used after it , this is one more application of boolean in C .