Why does a=(b++) have the same behavior as a=b++?

前端 未结 10 2090
借酒劲吻你
借酒劲吻你 2020-12-06 16:14

I am writing a small test app in C with GCC 4.8.4 pre-installed on my Ubuntu 14.04. And I got confused for the fact that the expression a=(b++); behaves in the

10条回答
  •  孤街浪徒
    2020-12-06 17:07

    Placing ++ at the end of a statement (known as post-increment), means that the increment is to be done after the statement.

    Even enclosing the variable in parenthesis doesn't change the fact that it will be incremented after the statement is done.

    From learn.geekinterview.com:

    In the postfix form, the increment or decrement takes place after the value is used in expression evaluation.

    In prefix increment or decrement operation the increment or decrement takes place before the value is used in expression evaluation.

    That's why a = (b++) and a = b++ are the same in terms of behavior.

    In your case, if you want to increment b first, you should use pre-increment, ++b instead of b++ or (b++).

    Change

    a1 = (b1++);
    

    to

    a1 = ++b1; // b will be incremented before it is assigned to a.
    

提交回复
热议问题