while loop requires explicit condition, for loop doesn't, why?

前端 未结 6 1081
抹茶落季
抹茶落季 2021-01-03 20:51

In C++ you are allowed to have an empty condition inside the for-loop, for example as in for (;;) or for (int x = 0;; ++x). But you can\'t do

6条回答
  •  没有蜡笔的小新
    2021-01-03 21:27

    In C++ you are allowed to have an empty condition inside the for-loop ... what's the argument behind not letting while() be an alias of while(true)?

    First of all, C++ (and C# and many other languages) are the way they are for backwards compatibility with C, so let's talk about C.

    Let's make some statements and draw a conclusion.

    1. There is a good reason why the for loop allows you to omit the condition.
    2. The same good reason applies to the while loop.
    3. The while loop does not allow the condition to be omitted; it is inconsistent.
    4. Consistency of design choices across statements is an important factor in the design of C.
    5. Therefore there must be an unobvious good reason for the inconsistency; there must be a good reason why the while loop is inconsistent with the for loop.

    And now the question is "what is that unobvious good reason?"

    But the question only makes sense if the chain of logic described above is correct, which it is not. Of those statements, only #3 is actually true! The for loop in C is a poor design; it's redundant, confusing for novices and its lexical conventions are inconsistent with the rest of the language. It provides almost zero additional representational power to the language over a straightforward while loop.

    There is no answer to your question; the correct response is rather to reject the premise of the question entirely. The for loop only seems reasonable because it's a 40+ year old misfeature that most of us grew up with, so its quirks are second nature now; this is familiarity, not good design. Had we grown up without the for loop, we wouldn't be adding it.

提交回复
热议问题