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

后端 未结 6 988
广开言路
广开言路 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:21

    For C

    Let's look at Kernighan & Ritchie original justification (original K&R page 42 and 43):

    The unusual aspects is that ++ and -- may be used either as prefix or as postfix. (...) In the context where no value is wanted (..) choose prefix or postfix according to taste. But htere are situations where one or the other is specifically called for.

    The text continues with some examples that use increments within index, with the explicit goal of writing "more compact" code. So the reason behind these operators is convenience of more compact code.

    The three examples given (squeeze(), getline() and strcat() ) use only postfix within expressions using indexing. The authors compare the code with a longer version that doesn't use embedded increments. This confirms that focus is on compactness.

    K&R highlight on page 102, the use of these operators in combination with pointer dereferencing (eg *--p and *p--). No further example is given, but again, they make clear that the benefit is compactness.

    For C++

    Bjarne Stroustrup wanted to have C compatibility, so C++ inherited prefix and postfix increment and decrement.

    But there's more on it: in his book "The design and evolution of C++", Stroustrup explains that initially, he planned have only one overload for both, postfix and prefix, in user defined classes:

    Several people, notably Brian Kernighan, pointed out that this restriction was unnatural from a C perspective and prevented users from defining a class that could be used as replacement for an ordinary pointer.

    Which caused him to find the current signature difference to differentiate prefix and postfix.

    By the way, without these operators C++ would not be C++ but C_plus_1 ;-)

提交回复
热议问题