-5
#include <stdio.h>
int main()
{
   int i=-3,j=2,k=0,m;
   m = ++i || ++j && ++k;
   printf("%d %d %d %d", i, j, k, m);
}

Output :

-2 2 0 1

Why should the expression m=++i||++j&&++k; not parsed as m=++i||(++j&&++k) as the precedence of && is higher than || ??

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100

1 Answers1

2

|| and && are short circuit operators. If the final result is evaluated from the left operand, right operand is not evaluated.

++i ||  /* Evaluate ++i which is -2, so the result of expression is 1 */
  ++j && ++k;  /* No need to evaluated this */
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • This is not guaranteed and is specific to compiler implementation. – Atmocreations May 26 '15 at 07:52
  • 5
    No, this is guaranteed by the specs – Mohit Jain May 26 '15 at 07:53
  • @Atmocreations logical operators in C-like languages are always shortcircuited by standard – phuclv May 26 '15 at 07:55
  • 2
    @Atmocreations 6.5.13/4 `"...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."` The standard can't really be more clear than that. – Lundin May 26 '15 at 08:36