I’ve been using the code below to read two different matrices from text files.
The code repeatedly re-declares (at least, I think it re-declares) the local variables stringvalues and iss. I just now realized that the variables are re-declared–I certainly didn’t intend to re-declare them.
Question: what is the effect of repeatedly re-declaring these variables?
FYI: I’m compiling with 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();
Yes, it re-declares them. But each declaration is actually a different variable. Much like if you called something
xin two different function declarations.That variable is showing up declared at the beginning of a block. A variable goes ‘out-of-scope’ (i.e. it’s destroyed and doesn’t exist anymore) after the block in which it was declared ends.
In fact, that variable is destroyed and re-created once for every single iteration of the
forloop. Each time it has the same name, but is conceptually a completely different variable (even if it occupies the same spot in memory).Also, if you tried to use the variable
stringvaluesbetween the twoforloops, the compiler would give you an error because the variable doesn’t exist there.So, even though those two variable declarations declare variables with the same name, those variables are actually different variables. You could just rename the one in the second block to have a
1on the end of the name and the effect would be exactly the same.