Boolean in C with Examples - Scaler Topics (2024)

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 with Examples - Scaler Topics (1)

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 in C with Examples - Scaler Topics (2)

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.

Boolean in C with Examples - Scaler Topics (3)

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.

Boolean in C with Examples - Scaler Topics (4)

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

Boolean in C with Examples - Scaler Topics (5)

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.

Boolean in C with Examples - Scaler Topics (6)

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

Boolean in C with Examples - Scaler Topics (7)

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,

Boolean in C with Examples - Scaler Topics (8)

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 .
Boolean in C with Examples - Scaler Topics (2024)

FAQs

What is an example of a boolean in C? ›

Boolean arrays: the user can use boolean arrays to store a collection of boolean values in C. For example: bool weekdays[7] = { true, true, true, true, true, false, false }; The above code declares an array of size 7 .

What are some examples of boolean? ›

Building Boolean expressions
Boolean ExpressionResult
x + y < 11FALSE
x * y = 21TRUE
x / y > 10FALSE
x + (2 * y) = 13TRUE
Mar 21, 2022

How to pass a boolean function in C? ›

Syntax
  1. #include <stdio.h>
  2. #include<stdbool.h>
  3. int main()
  4. {
  5. bool x=false; // variable initialization.
  6. if(x==true) // conditional statements.
  7. {
  8. printf("The value of x is true");

What are Boolean expressions in C? ›

Boolean expressions are the expressions that evaluate a condition and result in a Boolean value i.e true or false. Ex: (a>b && a> c) is a Boolean expression. It evaluates the condition by comparing if 'a' is greater than 'b' and also if 'a' is greater than 'c'.

What is a real life example of a Boolean? ›

Real world use cases

Example 1: On a most electronic household devices you would use a switch/button to control the on/off state of the device, this state is representative of a Boolean value as the device can only be on or off (True or false, 1 or 0).

What are the 3 main Boolean operators? ›

Boolean operators are the words "AND", "OR" and "NOT". When used in library databases (typed between your keywords) they can make each search more precise - and save you time!

What is a Boolean function with example? ›

A Boolean function refers to a function having n number of entries or variables, so it has 2n number of possible combinations of the given variables. Such functions would only assume 0 or 1 in their output. An example of a Boolean function is, f(p,q,r) = p X q + r.

Can you give an example of Boolean search? ›

Boolean Search Symbols & Terms

Or: The OR keyword tells the search to look for instances with either of the phrases entered. For example, searching for candidates who have "Java" OR "HTML" in their profile. And: The AND keyword tells the search to look for instances with both phrases entered.

Is there a Boolean data type in C? ›

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.

Can boolean be null in C? ›

A bool is literally that - a boolean value. So either 1 or 0 - true or false. In C only pointers can be NULL.

Why is there no boolean in C? ›

C didn't originally have bool , and maybe it still doesn't. It would simply be defined as some kind of int , possibly unsigned , with #define false 0 and #define true 1 . Just like NULL isn't a keyword either, but rather some #define thing. This is now so standard that it looks like bool is part of the language.

How to declare a string in C? ›

Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must use the char type and create an array of characters to make a string in C: char greetings[] = "Hello World!"; Note that you have to use double quotes ( "" ).

What is the default value of a Boolean in C? ›

The default value of the bool type is false .

How to call a function in C? ›

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. Control of the program is transferred to the user-defined function by calling it.

What are the data types in C? ›

There are four basic data types in C programming, namely Char, Int, Float, and Double.

What is an example of a Boolean operator? ›

The most popular Boolean commands are AND, OR, and NOT. Other commands include parentheses, truncation, and phrases.

Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated:

Views: 6245

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.