Table of Contents
Logical operators can be combined to form expressions containing multiple conditions. Parentheses can be used to explicitly control how the conditions are grouped.
#include <stdio.h>
int main()
{
int age = 25;
int has_id = 1;
int has_permission = 0;
if ((age >= 18 && has_id) || has_permission)
{
printf("Access granted\n");
}
return 0;
}
Example Output #
Access granted
Explanation #
The condition contains both && and ||:
(age >= 18 && has_id) || has_permission
The expression is grouped as:
(age >= 18 && has_id)
and:
has_permission
The first group is true because age >= 18 is non-zero and has_id is also non-zero. Therefore, the || expression is true, regardless of the value of has_permission.
Parentheses make the intended grouping explicit. Without parentheses, && has higher precedence than ||, so an expression such as:
a || b && c
is evaluated as:
a || (b && c)