gpt4 book ai didi

C++ 重新声明局部变量有什么作用?

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:51 27 4
gpt4 key购买 nike

我一直在使用下面的代码从文本文件中读取两个不同的矩阵。代码反复重新声明(至少,我认为它重新声明)局部变量 stringvaluesiss。我现在才意识到变量被重新声明了——我当然不打算重新声明它们。

问题:重复重新声明这些变量有什么影响?

仅供引用:我正在使用 GCC 4.4.3 进行编译。

fstream PW3_in("./input/PW.txt", ios::in);
for(int i=0; i<900; i++)
{
PW3_in.getline(line, 450);

string stringvalues;
stringvalues = line;
istringstream iss (stringvalues,istringstream::in);

iss >> word1 >> word2 >> word3 >> word4 >> word5 >> word6 >> word7 >> word8 >> word9;

num1 = strtod(word1, NULL);
num2 = strtod(word2, NULL);
num3 = strtod(word3, NULL);
num4 = strtod(word4, NULL);
num5 = strtod(word5, NULL);
num6 = strtod(word6, NULL);
num7 = strtod(word7, NULL);
num8 = strtod(word8, NULL);
num9 = strtod(word9, NULL);

PW3[0+i*9]=num1;
PW3[1+i*9]=num2;
PW3[2+i*9]=num3;
PW3[3+i*9]=num4;
PW3[4+i*9]=num5;
PW3[5+i*9]=num6;
PW3[6+i*9]=num7;
PW3[7+i*9]=num8;
PW3[8+i*9]=num9;

}
PW3_in.close();


fstream PP3_in("./input/PP.txt", ios::in);
for(int i=0; i<900; i++)
{
PP3_in.getline(line, 450);

string stringvalues;
stringvalues = line;
istringstream iss (stringvalues,istringstream::in);

iss >> word1 >> word2 >> word3 >> word4 >> word5 >> word6 >> word7 >> word8 >> word9;

num1 = strtod(word1, NULL);
num2 = strtod(word2, NULL);
num3 = strtod(word3, NULL);
num4 = strtod(word4, NULL);
num5 = strtod(word5, NULL);
num6 = strtod(word6, NULL);
num7 = strtod(word7, NULL);
num8 = strtod(word8, NULL);
num9 = strtod(word9, NULL);

PP3[0+i*9]=num1;
PP3[1+i*9]=num2;
PP3[2+i*9]=num3;
PP3[3+i*9]=num4;
PP3[4+i*9]=num5;
PP3[5+i*9]=num6;
PP3[6+i*9]=num7;
PP3[7+i*9]=num8;
PP3[8+i*9]=num9;

}
PP3_in.close();

最佳答案

是的,它重新声明了它们。但每个声明实际上是一个不同的变量。就像您在两个不同的函数声明中调用了某些东西 x 一样。

该变量显示在 block 的开头声明。在声明它的 block 结束后,变量“超出范围”(即它被销毁并且不再存在)。

事实上,对于 for 循环的每次迭代,该变量都会被销毁并重新创建一次。每次它都有相同的名称,但在概念上是一个完全不同的变量(即使它在内存中占据相同的位置)。

此外,如果您尝试在两个 for 循环之间使用变量 stringvalues,编译器会报错,因为该变量不存在。

因此,即使这两个变量声明声明的变量具有相同的名称,但这些变量实际上是不同的变量。您可以将第二个 block 中的那个重命名为名称末尾有一个 1,效果将完全相同。

关于C++ 重新声明局部变量有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com