Search code examples
cif-statementconditional-statementslogic

Why no brackets needed among conditions in if sentence?


int num;
scanf("%d", &num);

if (num % 4 == 0 && num%100 != 0 || num % 400 == 0)
    printf("%d", 1);
else
    printf("%d", 0);

In this logic, I found I do not need to do () in AND condition which is in front of OR condition. if (*(num % 4 == 0 && num%100 != 0)* || num % 400 == 0)

It's only needed if (num % 4 == 0 && num%100 != 0 || num % 400 == 0) without () in front of OR condition. so, it seems (A && B || C) works like ((A && B) || C) but it seemed it could work as (A && (B || C)) condition.

Why is () not needed in this situation? A and B condition are automatically grouped from the beginning?


Solution

  • All operators in C (and in fact all languages) have what's called operator precedence which dictates which operands are grouped first.

    The logical AND operator && has a higher precedence than the logical OR operator ||, which means that this:

    A && B || C
    

    Is the same as this:

    (A && B) || C
    

    So if you want B || C to be grouped together, you need to explicitly add parenthesis, i.e.:

    A && (B || C)