HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C Booleans



Booleans

In C, booleans represent logical values, either true or false. While there's no dedicated bool data type in standard C (C89), there are three ways to work with Booleans:

For this, C has a bool data type, which is known as booleans.

Booleans represent values that are either true or false.


Boolean Variables

C supports boolean variables to represent two logical values: true and false.

It was introduced in C99, and you must import the following header file to use it:

Example

#include <stdbool.h>


A boolean variable is declared with the bool keyword and can only take the values true or false:


Example Card

bool isProgrammingFun = true;

bool isFishTasty = false;


Before trying to print the boolean variables, you should know that boolean values are returned as integers:

1 (or any other number that is not 0) represents true

0 represents false

Therefore, you must use the %d format specifier to print a boolean value:


Example

#include <stdio.h>

#include <stdbool.h> // Import the boolean header file

int main() {

bool isProgrammingFun = true;

bool isFishTasty = false;

printf("%d\n", isProgrammingFun); // Returns 1 (true)

printf("%d", isFishTasty); // Returns 0 (false)

return 0;

}


Output

1

0


However, it is more common to return a boolean value by comparing values and variables.


Comparing Values and Variables

Comparing values and variables is a fundamental concept in C programming. It allows you to make decisions and control the flow of your program. Here's a breakdown of the key points:


Example

#include <stdio.h>

int main() {

printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9

return 0;

}


Output

1


From the example above, you can see that the return value is a boolean value (1).

You can also compare two variables:


Example

#include <stdio.h>

int main() {

int x = 10;

int y = 9;

printf("%d", x > y); // Returns 1 (true) because 10 is greater than 9

return 0;

}


Output

1


In the example below, we use the equal to (==) operator to compare different values:


Example

#include <stdio.h>

int main() {

printf("%d\n", 10 == 10); // Returns 1 (true), because 10 is equal to 10

printf("%d\n", 10 == 10); // Returns 1 (true), because 10 is equal to 10

printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to 55

return 0;

}


Output

1

1

0


You are not limited to only compare numbers. You can also compare boolean variables, or This includes integers, floating-point numbers, and other numeric data types. You can use the standard comparison operators like <, >, <=, >=, ==, and != to compare them.


Example

#include <stdio.h>

#include // Import the boolean header file

int main() {

bool isHamburgerTasty = true;

bool isPizzaTasty = true;

printf("%d", isHamburgerTasty == isPizzaTasty);

return 0;

}


Output

1