Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Why can't you declare a variable inside a do while loop? the OP asks why a declaration in the while-condition of a do-while loop isn't in scope in the do-statement. That would be very unnatural as C/C++ generally follow a "declaration-at-top-of-scope" pattern. But what about the converse - why not extend the scope of any declaration in the do-statement to the while-condition. That would allow

int i;
do {
  i = get_data();
  // whatever you want to do with i;
} while (i != 0);

to be shortened to

do {
  int i = get_data();
  // whatever you want to do with i;
} while (i != 0);

which gives a tidy syntax for limiting the scope of the control variable. (Note: I'm aware that this isn't valid syntax - that's the point of the question, why not extend the language to allow this syntax.)

As I note in a comment below, this extension would not break existing code, and would be very much in then spirit of the introduction of for-init (and while-init) scoping.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your proposal, the while statement while (i != 0); is out of the scope
of the inner block { int i = get_data(); }

It doesn't "see" the variable i, so it doesn't work.

Changing the language to support that would break one of its rules. Scoping is more important than the problem you show, which has a simple solution of declaring the variable before the block.

Also introducing your rule would break existing code as this valid example shows:

int i = 0 ;
do {
  int i = 1 ;
} while (i) ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...