In C programming, logical operators are used to combine multiple relational expressions to form a more complex
expression. Logical operators operate on Boolean values (true or false) and return a Boolean value. There are
three logical operators in C: && (logical AND), || (logical OR), and ! (logical NOT).
The logical AND operator returns true if and only if both operands are true; otherwise, it returns
false. The syntax for logical AND is:
expression1 && expression2
if(a > 0 && b < 10) { // do something }
In this example, if the value of variable 'a' is greater than zero AND the value of variable
'b' is less than ten, then the statement inside the curly braces will be executed.
Real-life example: In a security system, a door may require two inputs to be true in order to unlock
the door. For example, a user may need to enter a password AND swipe a security card to gain access.
The logical OR operator returns true if at least one of the operands is true; otherwise, it returns false. The syntax
for logical OR is:
expression1||expression2
if(x < 0 || y > 10) { // do something }
In this example, if the value of variable 'x' is less than zero OR the value of variable 'y' is greater than
ten, then the statement inside the curly braces will be executed.
The logical NOT operator reverses the truth value of an expression. If the expression is true, it returns false; if the expression
is false, it returns true. The syntax for logical NOT is:
!expression
if(!(a == b)) { // do something }
In this example, if the value of variable 'a' is NOT equal to the value of variable 'b', then the statement inside the curly braces
will be executed.
C language supports short-circuit evaluation for logical operators. This means that if the result of an expression can be determined by evaluating only
one operand, the other operand will not be evaluated. For example, in the expression (a && b), if the value of 'a' is false, the value of 'b' does not
need to be evaluated since the entire expression will be false regardless of the value of 'b'.
Example: if(ptr != NULL && *ptr > 0) { // do something }
In this example, if the pointer 'ptr' is NULL, the second operand (*ptr > 0) will not be evaluated. This prevents the program from crashing due to a null
pointer dereference.
Logical operators are commonly used in decision-making statements to control the flow of a program. For example, an if statement may use logical operators to determine
whether or not to execute a block of code. Logical operators are also used in loops to control the iteration of the loop based on certain conditions. Understanding
logical operators is essential for creating effective and efficient C programs.