Boolean in C Language

Booleans are a fundamental data type in the C programming language that represents true or false values. Booleans can have two possible values: "true" or "false". They are used extensively in decision-making and control structures to determine the flow of a program. In this tutorial, we will explore how to work with Booleans in C and understand their usage.

Note:You must include the header file when working with bool variables.

Declaring Boolean Variables

In C, there is no built-in Boolean data type. However, we can simulate Boolean values using integers or characters. Typically, we use 0 to represent false and any non-zero value to represent true. To declare a Boolean variable, we can use the "int" data type as follows:

Assigning Boolean Values

To assign a value to a Boolean variable, we can use the assignment operator (=). For example:

Boolean Expressions

Boolean expressions are statements that evaluate to either true or false. These expressions are commonly used in conditional statements such as if statements, while loops, and for loops. The comparison operators in C, such as == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to), can be used to form Boolean expressions.

Here's an example:

In this example, the result variable will store the value 0 because the expression num1 > num2 evaluates to false.

Boolean Operators

C provides three logical operators that are commonly used with Boolean values: && (logical AND), || (logical OR), and ! (logical NOT).

  • The logical AND (&&) operator returns true if both operands are true; otherwise, it returns false.
  • The logical OR (||) operator returns true if at least one of the operands is true; otherwise, it returns false.
  • The logical NOT (!) operator reverses the logical state of its operand. If the operand is true, it returns false, and if the operand is false, it returns true.

Here's an example that demonstrates the usage of these operators:

In this example, result1 will be true because both conditions are true, result2 will also be true because at least one condition is true, and result3 will be false because the condition is true and is negated by the logical NOT operator.

Boolean Functions

In C, you can define your own functions that return Boolean values. The return type of these functions can be declared as "int" since we are using integers to represent Booleans.

Here's an example of a Boolean function:

You can then use this function in your code as follows:

Booleans play a vital role in C programming when it comes to decision-making and control structures. By understanding how to declare Boolean variables, assign Boolean values, use Boolean expressions, and work with Boolean operators, you can write C programs that make decisions based on true or false conditions.