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

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c++ - Scope of declarations in the body of a do-while statement

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

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

1 Answer

0 votes
by (71.8m points)

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) ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...