Search code examples
coperatorsoperator-precedencesequence-pointslogical-and

C Operators and Precedence


I'm using C language, for the below code:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int num1=0;

    int res = ++num1 && num1++;

    printf("%d\t%d\n",num1,res);    
}

In the above code I get output as 2 1. I think the output should be 2 0.

Please correct me if wrong, to solve this statement, the num1++(0) would be executed first due to highest precedence and then ++num1(2) would be executed and then at last && will be preformed because it has the lowest precedence.

Please comment how is this statement getting executed.

In some of the tutorials I find that postfix ++ and prefix ++ have the same precedence, but if that is true then according to the associativity rule again num1++ should be executed first(right to left) which should again lead to answer as 2 0.


Solution

  • Lots of misconceptions here. First of all, operator precedence states the order of parsing, not the order of execution. There are two related but different terms, operator precedence and order of evaluation.
    See What is the difference between operator precedence and order of evaluation?.

    Once you understand order of evaluation, the && operator specifically comes with well-defined sequencing, which isn't normally the case for C operators. It guarantees a left-to-right order of evaluation. C17 6.5.14/4:

    Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

    Normally, you wouldn't be able to wild and crazy things with the ++ operator mixed with other operators, but the above && rule makes it possible in this specific case.

    See Why can't we mix increment operators like i++ with other operators? It explains sequencing/sequence points.


    In some of the tutorials I find that postfix ++ and prefix ++ have the same precedence,

    They don't, prefix ++ takes precedence over postfix (and other unary operators). So associativity does not apply.