Sunday, 21 April 2013

Short-circuiting in Logical AND

int main()
  int a;  
  a && printf("%d",a) && printf("LOL");  
  return 0;

If you give an input other than 0 say 2 then the output will be 2LOL and if you input a 0 then nothing will be printed. According to C-99 standard 6.5.13 paragraph 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
Now when the input is 0 then the first operand a is zero and according to standard rest of the expression will not be executed. If the output is non-zero then the first operand is not zero thats why second operand of && is executed and it prints the value of a and last operand prints LOL.

No comments:

Post a Comment