Ambiguity about ++ operator Associativity

237 views Asked by At

"C How to Program 6th edition - page 119" says that the associativity of ++ operator is "right to left". I wonder what does this mean, because ++ is a unary operator so in what case I may experience the associativity of a unary operator? Can you give me an example?

On the other hand, some net resources give different associativity for ++ operator based on its state (being prefix or postfix). While the book gives "right to left" associativity for postfix and prefix together, so which one is correct?

I will thanks full if you give me an example about ? associativity as well.

Thanks and regards

3

There are 3 answers

5
AudioBubble On

The associativity is only relevant when you have more than one operator applied to an argument. All the operators in group 3 share the same priority, if you happen to apply more than one operator from that group to an argument, they will be resolve according to the associativity rule of that group (right to left in that case).

~++x != ++~x

++ is indeed LTR in suffix and RTL in prefix position.

0
M.M On

C syntax is defined by a grammar. "Precedence" and "associativity order" are not part of the C standard. The purpose of a "precedence table" is so that a human can quickly make reference without having to read over all of the grammar. Sometimes such a table doesn't exactly capture everything that the grammar does.

Since operators cannot operate on operators, it doesn't make much sense to use "associativity" with a unary operator. I would advise just to ignore any such comments.

For example, E++++ can only be (E++)++, and ++++E can only be ++(++E). The language doesn't allow (++(++))E, although other languages might allow that sort of thing.

1
Armali On

"C How to Program 6th edition - page 119" says that the associativity of ++ operator is "right to left". I wonder what does this mean, because ++ is a unary operator so in what case I may experience the associativity of a unary operator?

"The C Programming Language, Second Edition, ANSI C" by Kernighan/Ritchie also says this. Obviously this assertion does not differentiate between prefix and postfix ++, but can nevertheless be regarded as true. Consider the unary-expression ++E++. (It is syntactically correct, only semantically wrong because it violates the constraint that the operand shall be an lvalue.) It constitutes no syntax error and is equivalent to ++(E++). Whether we can observe this associativity depends among other things on the expressiveness of the compiler's error message. We can get e. g. gcc to tell us by using the similar expression --E++ (with -- having identical precedence to ++); it produces a message

error: lvalue required as decrement operand

showing that the increment operator on the right-hand side was associated first.