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

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

    Incrementing and decrementing by 1 were widely supported in hardware at the time: a single opcode, and fast. This because "incrementing by 1" and "decrementing by 1" were a very common operation in code (true to this day).

    The post- and predecrement forms only affected the place where this opcode got inserted in the generated machine code. Conceptually, this mimics "increase/decrease before or after using the result". In a single statement

    i++;
    

    the 'before/after' concept is not used (and so it does the same as ++i;), but in

    printf ("%d", ++i);
    

    it is. That distinction is as important nowadays as it was when the language C was designed (this particular idiom was copied from its precursor named "B").

    From The Development of the C Language

    This feature [PDP-7's "`auto-increment' memory cells"] probably suggested such operators to Thompson [Ken Thompson, who designed "B", the precursor of C]; the generalization to make them both prefix and postfix was his own. Indeed, the auto-increment cells were not used directly in implementation of the operators, and a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1.

    Thanks to @dyp for mentioning this document.

提交回复
热议问题