Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the increment operator work in an if statement?

    #include <stdio.h>

    int main()
    {
        int x = 0;

        if (x++)
            printf("true\n");
        else if (x == 1)
            printf("false\n");
        return 0;
    }

Output:

false

Why is the output false?

x++ is post increment; this means that the value of x is used then it is incremented. If it is so, then x=0 should be used and the answer should be true.

like image 485
Pankaj Mahato Avatar asked Dec 02 '22 17:12

Pankaj Mahato


2 Answers

In C, 0 is treated as false. In x++, the value of x, i.e, 0 is used in the expression and it becomes

if(0)  // It is false
    printf("true\n");  

The body of if doesn't get executed. After that x is now 1. Now the condition in else if, i.e, x == 1 is checked. since x is 1 , this condition evaluates to true and hence its body gets executed and prints "false".

like image 98
haccks Avatar answered Dec 18 '22 10:12

haccks


Post increment means that it returns the current value (in this case for the purpose of the if) and increments it afterwards. It is equivalent to

if(x) {
  x++;
  // ...
} else {
  x++;
  // ...
}
like image 29
Sergey L. Avatar answered Dec 18 '22 10:12

Sergey L.