问题描述
我们可以这样做:
使用(流S ..)
和
的for(int我...)
我们为什么不能也做这样的事情:
,而((INT I = NextNum())0){..}
我发现它非常有用和明智的。
我不是一个语言的设计师,但我给它一个受过教育的猜测。
内的子句而()
执行循环的每一次执行。 (末尾+1更多的时间。)语句 INT I = NextNum()
声明了一个局部变量。你不能声明一个局部变量超过一次。
更新
语义,这是有道理的,这应该是可能的。事实上,正如在评论中指出的那样,这是可能的其他语言。然而,这不会没有重新编写一些主要的语法规则是在C#可能
局部变量必须在一份声明中声明。我相信语言,因为不是真正执行的变量声明这种方式分开。当你看到一行code的创建一个变量,并为其分配一个值,实际上仅仅是两个语句的快捷方式。从的:
void F() {
int x = 1, y, z = x * 2;
}
void F() {
int x; x = 1;
int y;
int z; z = x * 2;
}
The variable declaration part by itself is not "executed". It just means that there should be some memory allocated on the stack for a certain type of variable.
The while
statement is expecting a boolean expression, but an expression cannot be composed of a statement -- without a special casing some new grammar.
The for
loop is specially designed to declare a local variable, but you'll note that declaration part is "executed" only once.The using
statement was specifically designed to declare local variables (and dispose of them). It is also "executed" only once.
Also consider that a local variable declaration doesn't return a value -- it can't since the it allows you to declare multiple variables. Which value would this statement return?
int x = 1, y, z = x * 2;
The above statement is a local-variable-declaration. It is composed of a type, and three local-variable-declarators. Each one of those can optionally include an "=" token and a local-variable-initializer To allowing a local variable to be declared in this manner would mean that you pull apart the existing grammar a bit since you would need the type specifier, but mandate a single declarator so that it could return a value.
Enabling this behavior may nave negative side effects also, Consider that the while
and do
/while
statements are opposite, but parallel. As a language designer, would you also enable the do
statement to declare a local variable? I don't see this as possible. You wouldn't be able to use the variable in the body of the loop because it wouldn't have been initialized yet (as of the first run). Only the while statement would be possible, but then you would destroy the parallelism between while
and do
statements.
这篇关于为什么我们不能定义一个while循环中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!