Does it make sense for unary operators to be associative?

后端 未结 4 2169
小鲜肉
小鲜肉 2020-12-06 10:45

The C++ operator precedence table from http://en.cppreference.com/w/cpp/language/operator_precedence (I know it\'s not normative, but the standard doesn\'t talk about preced

4条回答
  •  醉酒成梦
    2020-12-06 10:56

    Consider the following piece of code

    int *p;
    *p++;
    

    The expression *p++ can be evaluated as either (*p)++ (incrementing the object that p points to) or *(p++) (pointing to the next object pointed by p).

    Because unary operators are right associative the expression *p++ will be evaluated as *(p++). (I came up with this while reading Kernighan and Ritchie.)

    It seems that the precedence and associativity has been changed and postfix ++ has higher precedence than dereference * operator.

    According to C11 the above expression will be evaluated as *(p++).

    I hope this makes it more clear why unary operators have associativity.

    Thanks to Lucian Grigore for pointing this out.

提交回复
热议问题