![]() |
VOOZH | about |
In C, logical expressions are used to perform decision-making using logical operators such as && (AND) or || (OR) by combining multiple conditions. These expressions return either true (non-zero) or false (0).
The logical expression evaluation or its meaning depends on its truth table. Let's take a look:
First Operand (X) | Second Operand (Y) | AND Evaluation (X && Y) | OR Evaluation (X || Y) |
|---|---|---|---|
0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 |
1 | 0 | 0 | 1 |
1 | 1 | 1 | 1 |
Here in the above table we can see that AND only evaluates to true if both of its operands are true. While OR evaluates to true even if one of the operands is true. In all the cases other than that we will receive false.
We can see that && AND evaluates true only when both of its operands are true. Let's see with an example :
Either a or b or both are zero
First operand of && is true while the second one is false. It resembles third case in the above truth table. That is why, the result of the logical expression is false. We combined two conditions (a != 0) and (b != 0) logically using && operator which finally results in false value, that is why the else body is executed.
Note: Any non-zero value can be considered true or 1. But only zero is considered false.
We can see that ||OR evaluates true if any of its operands is true. We can change the above example and replace && with || and see what happens:
Either a or b are non zero.
The output is changed. The body of the if block is now being executed, which means that the logical expression evaluates to true. Let's break it down:
First operand of || is true while the second one is false. But || it only needs one of them to be true.
We can combine many different conditions into a compound expression using logical operators:
Either a and b are equal or greater than 0 or both
Keep in mind the operator precedence and associativity while writing these expressions to make sure the expression is evaluated as intended.
From the above, we can infer that:
This property can lead to an interesting optimization in the evaluation of logical expressions.
This property is called short circuit evaluation. We can verify this property using the following code:
else block Value of a: 10
In the above expression, condition (a < 0) is false, so the AND expression should result in false leading to the execution of else block. This is what happens in the program.
But the second operand of the AND is an assignment expression which changes the value of the variable a. But when we print the value of a at the end, it is still not changed. This means that second operand is not even evaluated, confirming the short circuit evaluation.
Just like logical AND example, we can also verify the short circuit evaluation for logical OR expressions.
if block Value of a: 10
The first condition is true, so second operand is not even evaluated (shown by no value change in a variable) in the OR expression.