2

Talking about the associativity of operators in C, I was wondering why there are differences associativities among operators that have the same precedence. for example, postfix increment and postfix decrement have left associativity; while prefix increment and prefix decrement have right associativity. Isn't it simple to have just left or right associativity for all the same precedence operators?

Are there any reasons behind that?

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
ipkiss
  • 13,311
  • 33
  • 88
  • 123

2 Answers2

7

Isn't it simple to have just left or right associativity for all the same precedence operators?

Yes and it is the case in C. May be you assumed that prefix and postfix have the same precedence which is wrong. Postfix has a higher precedence than prefix!

Also there is another curious case to consider as to why certain operators have certain associativity. From Wiki,

For example, in C, the assignment a = b is an expression that returns a value (namely, b converted to the type of a) with the side effect of setting a to this value. An assignment can be performed in the middle of an expression. (An expression can be made into a statement by following it with a semicolon; i.e. a = b is an expression but a = b; is a statement). The right-associativity of the = operator allows expressions such as a = b = c to be interpreted as a = (b = c), thereby setting both a and b to the value of c. The alternative (a = b) = c does not make sense because a = b is not an lvalue.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
0

Binary operators are all left-associative except the assignment operator which is right-associative.

Postfix operators are sometimes (for exemple in K&R 2nd) said to be right-associative but this is to express the idea they have higher precedence than unary operators.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • The table in K&R (2nd ed. page 48) is to blame for a whole lot of confusion regarding operator precedence in C. There, they incorrectly put postfix and prefix in the same precedence group, which is just wrong. This is one of many many reasons why K&R shouldn't be used for teaching/learning C, the book is filled with errors and bad practice. – Lundin Apr 10 '12 at 11:55
  • @lundin, funny how the book of the creators of C should be full of errors! – Shahbaz Apr 16 '12 at 12:02
  • 1
    @Shahbaz It's not strange, really. The original book was written in the dark ages, before C was even standardized, and before good programming practice was even invented. The book was updated to 2nd edition upon ANSI/ISO standardization, but still inherited plenty of errors and oddities from the past. And the book has not been updated to the latest standards. And any computer science book older than 20 years should probably be regarded as obsolete anyway. – Lundin Apr 17 '12 at 06:38