Search code examples
cshort-circuitingpost-increment

C Increment operators


I have compiled the code below in codeblocks and it shows the output 0...0 . But I think its output should be 0...1 because "if" statement is not true here so the statement following the "if" is not executed.Then j is incremented by 1 ( because of j++ in "if" statement ) but i remains 0. So , the last printf() should give 0...1 .

#include <stdio.h>

int main()
{
    int i =0,j=0;
    if(i && j++)
        printf("%d..%d\n",i++,j);
    printf("%d...%d",i,j);
    return 0;
}

Solution

  • See C11 6.5.13 Logical AND operator p4 (my emphasis)

    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.

    The first operand in your example is i. It compares equal to 0 so the second operand (j++) is not evaluated (executed). It is therefore correct that your later printf shows that j is still 0.