Search code examples
cpost-incrementpre-incrementand-operator

How does this code produces an output of 6 and 3?


#include<stdio.h>
void main() {
     int x = 0,y = 0,k = 0;
     for(k = 0; k < 5; k++){
         if(++x > 2 && ++y > 2)    x++;
     }
     printf("x = %d and y = %d",x,y);
}

I'm not able to understand how the above piece of code generates x = 6 and y = 3.

RESOLVED : I didn't know that when there is &&, if the first statement evaluates to false the second will not be executed.


Solution

  • && is a short-circuit operator.

    The first time through the loop, only ++x is evaluated.
    The second time through the loop, only ++x is evaluated.
    The third time through the loop, both are evaluated.
    ...