prefix , postfix operator associativity

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askpragnesh
    New Member
    • Sep 2006
    • 3

    prefix , postfix operator associativity

    hey all ! i am pragensh and joined today for follwoing reason
    can you help me how this output came ?
    x=3;
    x-=--x-x--;
    printf("x=%d",x );
    here answer is coming as 1 how come ?
    can you please help me to find the reason ? or
    step wise explaination
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    Putting two unary operations like that on the same line has undefined behavior, it's not ever a good idea. However, in your case, it looks like your compiler evaluates left to right. However, parenthesis come first. I substitute for x when I put it's value in parenthesis, i.e. --(3), (2)--, or (1).

    x = 3;
    x = x - (--x - x--)
    x = x - (--(3) - x--)
    x = x - (2 - x--)
    x = x - (2 - (2)--)
    x = x - (2 - 2)
    x = (1) - 0
    x = 1 - 0
    x = 1

    Comment

    • askpragnesh
      New Member
      • Sep 2006
      • 3

      #3
      Originally posted by D_C
      Putting two unary operations like that on the same line has undefined behavior, it's not ever a good idea. However, in your case, it looks like your compiler evaluates left to right. However, parenthesis come first. I substitute for x when I put it's value in parenthesis, i.e. --(3), (2)--, or (1).

      x = 3;
      x = x - (--x - x--)
      x = x - (--(3) - x--)
      x = x - (2 - x--)
      x = x - (2 - (2)--)
      x = x - (2 - 2)
      x = (1) - 0
      x = 1 - 0
      x = 1
      thank you sir but i am get back to you with some doubt regarding the same topic

      Comment

      • shankara
        New Member
        • Jan 2007
        • 2

        #4
        sir i think this is how the steps will go,but can u explain me your logic in steps (1) & (2)


        x = 3;
        x = x - (--x - x--)
        x = x - (--(3) - x--)
        x = x - (2 - x--)
        x = x - (2 - (2)--)
        x = x - (2 - 1) /* (sir according to postfix operation) */ .. (1)
        x = (2) - 1 (2)
        x = 2-1
        x = 1

        Comment

        Working...