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

前端 未结 6 1080
抹茶落季
抹茶落季 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:36

    I think the main difference is between expressions and statements.

    Sure, in C the two aren't rigorously distinguished, but I would say the for loop is:

    for (statement; expression; statement) {
        ...
    }
    

    The expression is a boolean expression, while the statements are...statements which have side effects. Of course, C isn't semi-functional; you can put side effects in the middle expression, but it isn't idiomatic.

    Yet sometimes you don't want an expression, but statements at the beginning and at each loop iteration is useful, so the middle expression is optional:

    // Infinite counter
    int i;
    for (i = 0;;i++) {
       ...
    }
    

    This by definition means that the expression is considered always true

    On the other hand, while and if can only take expressions. There is nothing very useful left (unlike the two useful statements left) if you omit that expression: nobody would write

    // Idiot coding
    if (true) {
       ...
    }
    

    because the point of an if statement is to check whether some unknown is true or not!

    Same thing with while. The point of while is to do something over and over as long as a condition in the form of an expression is true. It's kinda like an "iterated if". This is why

    while() {
       ...
    }
    

    is not considered logical and thus not allowed.

提交回复
热议问题