471,831 Members | 1,097 Online

# 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 ?
step wise explaination
Sep 14 '06 #1
3 3555
D_C
293 100+
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
Sep 14 '06 #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
thank you sir but i am get back to you with some doubt regarding the same topic
Sep 15 '06 #3
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
Jan 12 '07 #4