我不知道如何在循环(C++)之外引用变量
I cannot figure out how to refer to a variable outside a loop(C++)
基本上我的问题是我在循环外创建了一个变量(字符串),我想在循环内使用它。下面是一个示例代码,以尝试更好地解释:
int myage = 0; // set by user
int currentyear = 2015;
cout << "How old are you?" << endl;
cin >> myage;
for(int i=0; i>98; i++) {
myage=myage+1;
currentyear=currentyear+1;
cout << "In " << currentyear << " you will be " << myage << " years old." << endl;
}
这只是我为了更好地解释它而编造的一个快速示例,所以我的问题是:有什么方法可以在这个循环中使用myage
或currentyear
变量吗?如果是,如何?
不要犹豫,询问您是否需要更多信息或特定数据。
循环从不执行
for(int i=0; i>98; i++){
因为i>98
是false
如果你问什么,我认为你在问什么,绝对。for 循环几乎更像是一种方便的语法,它为您提供了一个指定初始条件、中断条件和执行每次迭代的命令的位置。据我所知,您可以根据需要使用其中的任意数量,例如
#include <iostream>
int main(){
int myage = 0;
for(; myage<10; myage++)
std::cout << myage << std::endl;
}
将打印出数字 0 到 9。
由于这个问题已经得到了回答,你可以通过使用 += 运算符来改进和缩短你的代码,如下所示: myage += 1;
或者这个: myage++;
而不是myage=myage+1;
了解范围很重要。循环和函数创建一个作用域,它们始终可以访问更高作用域的事物;但是,无法从较小的范围访问事物。对象在其作用域的整个持续时间内存在,并且该作用域中的任何内容都可以访问它们。
// Global scope:
int g = 0; // everything in this file can access this variable
class SomeClass
{
// Class scope
int c = 0;
void ClassFunction()
{
// ClassFunction scope
// Here we can access anything at global scope as well as anything within this class's scope:
int f = 0;
std::cout << g << std::endl; // fine, can access global scope
std::cout << c << std::endl; // fine, can access class scope
std::cout << f << std::endl; // fine, can access local scope
}
// Outside of ClassFunction, we can no longer access the variable f
};
void NonClassFunction()
{
// NonClassFunction scope
// We can access the global scope, but not class scope
std::cout << g << std::endl;
int n1 = 0;
for (...)
{
// New scope
// Here we can still access g and n1
n1 = g;
int x = 0;
}
// We can no longer access x, as the scope of x no longer exists
if (...)
{
// New scope
int x = 0; // fine, x has not been declared at this scope
{
// New scope
x = 1;
g = 1;
n1 = 1;
int n2 = 0;
}
// n2 no longer exists
int n2 = 3; // fine, we are creating a new variable called n2
}
}
希望这有助于向您解释范围。考虑到所有这些新信息,答案是肯定的:您可以在 for 循环中访问变量,因为这些变量的作用域保留在内部作用域中。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++方法中的引用变量
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 使用更改此变量的函数在同一行中打印引用变量
- 将延迟变量分配给引用变量
- 如何通过引用获取引用变量的地址?
- 将引用变量传递给函数
- C++中引用变量的内存?
- 按名称存储和引用变量列表
- 返回一个C++引用变量 VS 返回一个变量
- c++ 在 if 语句中分配引用变量
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- 在类范围内声明时,应在 C++14 中引用变量模板
- 当引用变量的引用"死亡"时,它会发生什么?
- 将非按引用变量分配给返回按引用的函数,反之亦然
- 引用变量如何存储在mem中
- 引用变量存储在哪里