Clarify the associativity

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    Clarify the associativity

    Code:
    int i=-3,j=2,k=0,m;
      m=++i||++j&&++k;
      printf("\ni=%d""\nj=%d""\nk=%d""\nm=%d",i,j,k,m);

    FOR THE ABOVE CODE my compiler gives the answer as
    i=-2, j=2, k= 0, m=1

    At first ++i||++j is evaluated. For the || operator if one operand is non-zero the result is non-zero.hence here i is increased to -2 and ++j is not evaluated...

    But after this -2 should be ANDed with k. Since for the && operation both the operands should be evaluated to find the result according to me K should be increased to 1. But here the K is not increased. Kindly clarify the reason pls
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    No. With parentheses, the expression is
    m=++i||(++j&&++ k);
    First, ++i is evaluated. As it is nonzero, the result of || operation is true (1) and the rest is not evaluated at all (short-circuit evaluation). i gets incremented to -2 and the other are not changed.

    Comment

    • vensriram
      New Member
      • Aug 2010
      • 48

      #3
      Thanks for your reply. But here the expression will be evaluated from left to right(imagine the condition without paranthesis) and hence I doubt the AND operation should take place.Kindly clarify

      Comment

      • newb16
        Contributor
        • Jul 2008
        • 687

        #4
        Parentheses make no difference as && has higher precedence than || , so they evaluate left to right, evaluating the left argument of || first, then (is if was 0) its right argument, which is ++j && ++k , not ++j alone.

        Comment

        • vensriram
          New Member
          • Aug 2010
          • 48

          #5
          Thanks newb16.......i have understood it clearly....

          Comment

          Working...