Operator associativity in C specifically prefix and postfix increment and decrement

后端 未结 3 1561
梦谈多话
梦谈多话 2021-01-06 05:24

In C operation associativity is as such for increment, decrement and assignment.

  2. postfix ++ and -- 
  3. prefix ++ and -- 
  16. Direct assignment = 
<         


        
3条回答
  •  借酒劲吻你
    2021-01-06 05:31

    As AndreyT already pointed out, precedence and associativity don't tell you about order of evaluation. They only tell you about grouping. For example, precedence is what tells use that a*b+c is grouped as (a*b)+c instead of a*(b+c). The compiler is free to evaluate a, b and c in any order it sees fit with either of those expressions. Associativity tells you about grouping when you have operators of the same precedence, most often, the same operators. For example, it's what tells you that a-b-c is equivalent to (a-b)-c, not a-(b-c) (otherwise stated, subtraction is left associative).

    Order of evaluation is defined by sequence points. There's a sequence point at the end of a full expression (among other things). At the sequence point, all the previous evaluations have to have taken place, and none of the subsequent evaluations can have taken place yet.

    Looking at your specific examples, in a=b++;, the result is mostly from the definition of post-increment itself. A post-increment yields the previous value of the variable, and sometime before the next sequence point, the value of that variable will be incremented. A pre-increment yields the value of the variable with the increment applied. In neither case, however, does that mean the variable has to be incremented in any particular order relative to the assignment. For example, in your pre-increment example, the compiler is entirely free to do something equivalent to:

    temp = b+1;
    a = temp;
    b = b + 1;
    

    Likewise, in the post-increment version, the variable can be incremented before or after the assignment:

    a = b;
    b = b + 1;
    

    or:

    temp = b;
    b = b + 1;
    a = temp;
    

    Either way, however, the value assigned to a must be the value of b before it's incremented.

提交回复
热议问题