Search code examples
cpostfix-operatorlogical-orprefix-operatorlogical-and

Prefix operators are not working as expected in C


#include <stdio.h>
int main()
{
    int a = 1;
    int b = 1;
    int c = a || --b;
    int d = a-- && --b;
    printf("a=%d, b= %d, c= %d, d= %d",a,b,c,d);
    return 0;
}

In th above code, I expected output to be a=0, b= -1, c= 1, d= 0 but the output was a=0, b= 0, c= 1, d= 0

Screenshot_VS Code


Solution

  • In the expression used as an initializer in this declaration

    int c = a || --b;
    

    as the operand a is not equal to 0 then the expression --b is not evaluated.

    So the variable c is initialized by 1.

    From the C Standard (6.5.14 Logical OR operator)

    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.

    In the expression used as an initializer in this declaration

    int d = a-- && --b;
    

    the operand a-- is not equal to 0 (the value of the postfix operator is the value of its operand before decrementing). So the operand --b is evaluated. As its value is equal to 0 then the variable d is initialized by 0.

    From the C Standard (6.5.13 Logical AND operator)

    4 Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

    As a result a and b will be equal 0 after this declaration.