Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Why can't I put a variable declaration in the test portion of a while loop?

You can, obviously, put a variable declaration in a for loop:

for (int i = 0; ...

and I've noticed that you can do the same thing in if and switch statements as well:

if ((int i = f()) != 0) ...

switch (int ch = stream.get()) ...

But when I try to do the same thing in a while loop:

while ((int ch = stream.get()) != -1) ...

The compiler (VC++ 9.0) does not like it at all.

Is this compliant behavior? Is there a reason for it?

EDIT: I found I can do this:

while (int ch = stream.get() != -1) ...

but because of precedence rules, that's interpreted as:

while (int ch = (stream.get() != -1)) ...

which is not what I want.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The grammar for a condition in the '03 standard is defined as follows:

condition:
  expression
  type-specifier-seq declarator = assignment-expression

The above will therefore only allow conditions such as:

if ( i && j && k ) {}
if ( (i = j) ==0 ) {}
if ( int i = j ) {}

The standard allows the condition to declare a variable, however, they have done so by adding a new grammar rule called 'condition' that can be an expression or a declarator with an initializer. The result is that just because you are in the condition of an if, for, while, or switch does not mean that you can declare a variable inside an expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...