What are the historical reasons C languages have pre-increments and post-increments?

后端 未结 6 973
广开言路
广开言路 2021-02-08 12:32

(Note: I am not asking about the definitions of pre-increment vs. post-increment, or how they are used in C/C++. Therefore, I do not think this is a duplicate question.)

6条回答
  •  盖世英雄少女心
    2021-02-08 13:26

    Consider the following loop:

    for(uint i=5; i-- > 0;)
    {
        //do something with i,
        // e.g. call a function that _requires_ an unsigned parameter.
    }
    

    You can't replicate this loop with a pre-decrement operation without moving the decrement operation outside of the for(...) construct, and it's just better to have your initialization, interation and check all in one place.

    A much larger issue is this: one can over-load the increment operators (all 4) for a class. But then the operators are critically different: the post operators usually result in a temporary copy of the class instance being made, where as the pre-operators do not. That is a huge difference in semantics.

提交回复
热议问题