1,745 views
1 votes
1 votes
int i=0,j=0;

if(i&&j++)printf (print I, j)

printf(print I, j)

output : is 0,0

My Question is..  ' if' statement is executed and failed as I and j have values 0,0

then why j is not incremented

output has to be 0,1 according to my knowledge. Even though if loop gets executed and failed j has to get incremented after if loop.  Why it is not happening?

Ps:  I'm not able to follow proper style in coding as I'm typing from mobile.  Please excuse

1 Answer

Best answer
1 votes
1 votes
int i=0,j=0;
if(i&&j++)
    printf ("i = %d, j = %d", i, j);
printf ("i = %d, j = %d", i, j);

&& is shorthand "AND" operator and is doing logical AND operation. As we know an AND GATE outputs a 1 only when both inputs are 1. So, C being smart evaluates first operand and if it is 0 won't evaluate the second and this is called short circuit rule in C.

It would be trivial to think that this is for efficiency reasons. But that is not so correct. Because this rule is actually restricting the start of the execution of the next instruction after '&&' until the result of the previous one is known which can restrict pipeline execution which is very common nowadays. But the real usage of this rule is in ensuring safety of the code like we can detect an error condition as part of the left operand to '&&' and do the actual check  in right operand - something like

if (a!= NULL && a-> data > 0)

The short circuit rule also exist for '||' (logical OR) operator. And these two operators are actually sequencing the execution in C and hence part of sequence points.

selected by

Related questions

4 votes
4 votes
1 answer
1
3 votes
3 votes
2 answers
3
0 votes
0 votes
1 answer
4
TusharKumar asked Dec 22, 2022
510 views
can anyone explain how the for loop works here..?