Logical and relational operators are both used in C programming, but they serve different purposes.
Relational Operators:
Relational operators are used to compare values and return a Boolean result (true or false). Here are the common relational operators in C:
- == (Equal to)
- != (Not equal to)
- > (Greater than)
- < (Less than)
- >= (Greater than or equal to)
- <= (Less than or equal to)
Example:
int a = 10, b = 5;
if (a == b) {
printf("a is equal to b");
} else {
printf("a is not equal to b");
}
In this example, the relational operator ==
is used to compare the values of a
and b
. Since they are not equal, the else
block will be executed.
Logical Operators:
Logical operators combine Boolean expressions and return a Boolean result. They are used to create more complex conditions. Here are the common logical operators in C:
- && (Logical AND)
- || (Logical OR)
- ! (Logical NOT)
Example:
int age = 25, isStudent = 1;
if (age >= 18 && isStudent == 1) {
printf("You are eligible for a student discount");
}
In this example, the logical operator &&
is used to combine two conditions: age >= 18
and isStudent == 1
. Both conditions must be true for the code inside the if
block to execute.
Key Differences:
- Purpose: Relational operators compare values, while logical operators combine Boolean expressions.
- Return Value: Both return a Boolean value (true or false).
- Usage: Relational operators are often used in conditional statements (
if
,else
,switch
), while logical operators are used to create more complex conditions within these statements.
Practical Insights:
- Logical operators are used to create more complex decision-making logic in your code.
- Relational operators are the building blocks for logical operators, forming the basis of comparisons.