在条件中使用在do-while循环中声明的变量 [英] Use variables declared inside do-while loop in the condition

查看:795
本文介绍了在条件中使用在do-while循环中声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写这样的代码:

do {
    int i = 0;
    int j = i * 2;
    cout<<j;

    i++;
} while (j < 100);

http:// codepad.org/n5ym7J5w

当我的编译器告诉我,我不能使用变量'j',因为它不是在do-while循环。

and I was surprised when my compiler told me that I cannot use the variable 'j' because it is not declared outside the do-while loop.

我只是很好奇,如果有任何技术上的原因,为什么这是不可能的。

I am just curious about if there is any technical reason why this cant be possible.

推荐答案

有一个原因,这是不可能的。这是由于语句范围的限制。

There is a reason why this can't be possible. It is due to the limitation of "statement-scope".

您的变量i和j已使用local scope(即{}括号内的变量)声明。你实际上希望j被声明为语句范围,但这是不可能的。

Your variables i and j have been declared with "local scope" -- that is variables inside {} brackets. You actually wanted j to be declared with "statement scope" but this is not possible.

语句范围是声明为'for','while' ,'if'或'switch'语句。

Statement-scope are those variables declared as part of 'for', 'while', 'if' or 'switch' statements. Statement scope does not cover do-while statements, though, which is why you cannot do this.

你基本上暴露了使用do-while的语言缺点。

You have basically exposed a language drawback of using do-while.

这将是更好的语言提供:

It would be better if the language offered:

do {
.
.
.
} while (int j < 100);

但不提供此项。

这篇关于在条件中使用在do-while循环中声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆