In the C programming language, there is no built-in data type called "Boolean." However, C supports Boolean values and expressions using integers. Typically, in C, 0
represents false
, and any non-zero value represents true
. In other words, C uses integer values to represent Boolean values, where 0
is considered false
, and anything other than 0
is considered true
.
C Booleans
As mentioned earlier, C does not have a dedicated Boolean data type, but you can use integers to represent Boolean values. Conventionally, 0
is used for false
, and any non-zero value (usually 1
) is used for true
.
#include
int main() {
int isTrue = 1; // true
int isFalse = 0; // false
printf("isTrue is %d\n", isTrue);
printf("isFalse is %d\n", isFalse);
return 0;
}
In this example, isTrue
is assigned 1
to represent true
, and isFalse
is assigned 0
to represent false
. You can use these variables in conditional statements, loops, and other control structures to make decisions in your program.
C Boolean Expressions
C Boolean expressions are expressions that evaluate to a Boolean value (true
or false
). They are often used in conditional statements (e.g., if
, else
, while
, for
) to control the flow of a program.
#include
int main() {
int num = 10;
if (num > 5) {
printf("num is greater than 5.\n"); // This block will be executed because the condition is true.
} else {
printf("num is not greater than 5.\n");
}
return 0;
}
In this example, the condition num > 5
is a Boolean expression. It evaluates to true
because the value of num
(10) is indeed greater than 5. As a result, the code within the if
block is executed.
C also provides logical operators that allow you to create more complex Boolean expressions. These operators include:
- &&
(logical AND)
- ||
(logical OR)
- !
(logical NOT)
#include
int main() {
int a = 5;
int b = 7;
if (a > 0 && b > 0) {
printf("Both a and b are greater than 0.\n");
} else {
printf("At least one of a and b is not greater than 0.\n"); // This block will be executed.
}
return 0;
}
In this example, the &&
operator combines two conditions. The if
block is executed only if both a > 0
and b > 0
are true
.
To summarize, C does not have a dedicated Boolean data type, but you can represent Boolean values using integers. Boolean expressions are used in conditional statements to control program flow, and you can create complex conditions using logical operators.