fork download
  1. #include <stdio.h>
  2.  
  3. int main() {
  4.  
  5.  
  6. int a = 1;
  7. int b = 0;
  8.  
  9. // Following two statements returns the same output
  10. printf("\nhah %d", a != 0 & b != 0); // returns 0
  11. printf("\nhah %d", a != 0 && b != 0); // returns 0
  12.  
  13. // Despite the common misconception that the statement 1 when written explicitly
  14. // is this...
  15. printf("\nmeh %d", (a != (0 & b)) != 0); // returns 1
  16. // ..., statement 1's AND(&) operator still retain the same operator precedence as its short-circuit cousin(&&)
  17.  
  18.  
  19. printf("\n");
  20.  
  21. const int ALT_KEY = 2;
  22. int input = 1;
  23.  
  24. // should return 0, it returns 0:
  25. printf("\nhah %d", (input & ALT_KEY) == ALT_KEY);
  26.  
  27. // despite the expectation that this "should" return 0, this doesn't return 0:
  28. printf("\nmeh %d", input & ALT_KEY == ALT_KEY);
  29.  
  30. // So it means, despite the introduction of short-circuit operator,
  31. // the non-short-circuit logical/bitwise operator (&,|) still retain their
  32. // operator precedence.
  33. // Hence, the unparenthesized expression (input & ALT_KEY == ALT_KEY), when written explicitly is still evaluated as:
  34. printf("\nhah %d", input & (ALT_KEY == ALT_KEY) ); // returns 1
  35.  
  36. // Similar with operator precedence of logical operator:
  37. printf("\nhah %d", input && ALT_KEY == ALT_KEY ); // returns 1
  38.  
  39. // Logical operator when written explicitly
  40. printf("\nhah %d", input && (ALT_KEY == ALT_KEY) ); // returns 1
  41.  
  42.  
  43.  
  44. printf("\n");
  45. }
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
hah 0
hah 0
meh 1

hah 0
meh 1
hah 1
hah 1
hah 1