Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is while's condition outside the do while scope

More often than not we need loops like this

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

Unfortunately this will not compile, because value's scope ends at }. Which means that I will have to declare it outside the loop.

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

I don't like this for at least two reasons. For one, I like declaring things locally. And second, this is a problem if value is not assignable or default-constructible, but only copy-constructible.

So, my question has two sides. First, I'd like to know if there was a particular reason/difficulty in extending the do while's scope to the final condition as well (just as the scope of variables declared in for loop includes the body of the for loop despite it physically being outside of the braces). And if you believe that the answer to my first question is "It's just the way it is. Don't ask why questions." then I'd like to know if there are idioms that can help write do-while loops similar to the ones in my example but without the downsides I mentioned.

Hope the questions are clear.

like image 576
Armen Tsirunyan Avatar asked Nov 08 '12 20:11

Armen Tsirunyan


People also ask

Does a while loop always run once?

The 'do-while' loop is a variation of the while loop. 'do-while' loops always execute at least once, whereas while loops may never execute.

What does a while statement do?

while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.


1 Answers

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"

like image 198
sampson-chen Avatar answered Oct 14 '22 10:10

sampson-chen