我不知道如何在循环(C++)之外引用变量

I cannot figure out how to refer to a variable outside a loop(C++)

本文关键字:引用 变量 C++ 循环 我不知道      更新时间:2023-10-16

基本上我的问题是我在循环外创建了一个变量(字符串),我想在循环内使用它。下面是一个示例代码,以尝试更好地解释:

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;
}

这只是我为了更好地解释它而编造的一个快速示例,所以我的问题是:有什么方法可以在这个循环中使用myagecurrentyear变量吗?如果是,如何?

不要犹豫,询问您是否需要更多信息或特定数据。

循环从不执行

for(int i=0; i>98; i++){

因为i>98false

如果你问什么,我认为你在问什么,绝对。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 循环中访问变量,因为这些变量的作用域保留在内部作用域中。