In C language, logical operators are used to combine multiple conditions or expressions, typically in conditional statements (if
, while
, etc.). These operators help control the flow of a program by evaluating multiple conditions together. There are three main logical operators in C: logical AND (&&
), logical OR (||
), and logical NOT (!
). The result of a logical operation is either true
(non-zero, usually 1) or false
(0).
List of Logical Operators
Logical AND (
&&
):- Returns
true
if both operands aretrue
. If either operand isfalse
, the result isfalse
. - Used when you want to check if all given conditions are
true
. - Example:
int a = 5, b = 10; if (a > 0 && b > 0) { // This block will execute because both conditions are true. }
- Returns
Logical OR (
||
):- Returns
true
if at least one operand istrue
. The result isfalse
only if both operands arefalse
. - Used when you want to check if any given condition is
true
. - Example:
int a = 5, b = -3; if (a > 0 || b > 0) { // This block will execute because at least one condition (a > 0) is true. }
- Returns
Logical NOT (
!
):- Reverses the truth value of the operand. If the operand is
true
, it returnsfalse
, and vice versa. - Used to invert a condition.
- Example:
int a = 5; if (!(a < 0)) { // This block will execute because a is not less than 0. }
- Reverses the truth value of the operand. If the operand is
Examples of Usage in Conditions
Logical operators are often used to create complex conditional statements:
#include <stdio.h>
int main() {
int x = 5, y = 10, z = 15;
// Logical AND
if (x > 0 && y > 0 && z > 0) {
printf("All numbers are positive.\n");
}
// Logical OR
if (x > 10 || y > 10 || z > 10) {
printf("At least one number is greater than 10.\n");
}
// Logical NOT
if (!(x > 10)) {
printf("x is not greater than 10.\n");
}
return 0;
}
Short-Circuit Evaluation
- AND (
&&
): If the first operand isfalse
, the second operand is not evaluated because the whole expression will befalse
. - OR (
||
): If the first operand istrue
, the second operand is not evaluated because the whole expression will betrue
.
For example:
int a = 0, b = 10;
if (a != 0 && b / a > 1) {
// This will not evaluate "b / a" since "a != 0" is false, avoiding division by zero.
}
Important Points
- Return Values: Logical operators return
1
(true) or0
(false). - Combining Conditions: Logical operators are useful for combining multiple conditions in
if
,while
, orfor
statements.
Summary
- Logical AND (
&&
):true
if all conditions aretrue
. - Logical OR (
||
):true
if at least one condition istrue
. - Logical NOT (
!
): Inverts the truth value of a condition.
Logical operators are essential for controlling the flow of a program by allowing you to combine and manipulate conditions effectively, making decision-making more flexible and powerful.