Why is while's condition outside the do while scope

后端 未结 1 488
天命终不由人
天命终不由人 2021-01-01 10:29

More often than not we need loops like this

do
{
     Type value(GetCurrentValue());
     Process(value);
}while(condition(value));

Unfortu

相关标签:
1条回答
  • 2021-01-01 10:42

    If you'd like to keep value locally scoped for the while loop, you can do this instead:

    do
    {
         Type value(GetCurrentValue());
         Process(value);
         if (! condition(value) )
             break;
    } while(true);
    

    This is just personal preference, but I find while loops structured like the following more readable (while instead of do-while):

    while(true) {
        Type value(GetCurrentValue());
        Process(value);
        if (! condition(value) ) {
            break;
        }
    }
    

    The scoping rules in C/C++ works as follows: Local variables declared within a brace {...} block is local / visible only to that block. For example:

    int a = 1;
    int b = 2; 
    {
        int c = 3;
    }
    std::cout << a;
    std::cout << b;
    std::cout << c;
    

    will complain about c being undeclared.

    As for rationale - it's just a matter of consistency and "that's just how the language is defined"

    0 讨论(0)
提交回复
热议问题