为什么我不能在while循环的测试部分中添加变量声明

为什么我不能在while循环的测试部分中添加变量声明

本文介绍了为什么我不能在while循环的测试部分中添加变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,你可以在一个for循环中加入一个变量声明:

  for(int i = 0; .. 。

我注意到你可以在if和switch语句中做同样的事情:

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

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

但是当我尝试做同样的在while循环中:

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

编译器(VC ++ 9.0)根本不喜欢。

:我发现我可以这样做:

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

但是由于优先规则,它被解释为:

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


$ b

解决方案

'03标准中条件的语法定义如下:

 条件:
表达式
type-specifier-seq declarator = assignment- expression

因此,上述条件只允许使用以下条件:

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

标准允许条件声明一个变量,然而,它们通过添加一个称为'condition'的新语法规则,可以是一个表达式或一个带初始化器的声明符。结果是,只是因为你处于的情况下 while switch 并不意味着您可以在表达式中声明一个变量。


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.

解决方案

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.

这篇关于为什么我不能在while循环的测试部分中添加变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:04