When printing a variable inside a loop I get an error message about a undeclared identifier. The variable that gives the error is "j".
// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i )
{
if (strcmp(candidates[i].name, name)==0)
{
for(int j = 1; j <candidate_count; j )
preferences[i][j] = rank;
printf("i = (%i) j = (%i)\n", i , j);
printf("prefenrences[i][j], (%i)(%i)\n", preferences[i][j]);
return true;
}
}
printf("text");
return false;
}
The error message I get is as followed:
" runoff.c:137:43: error: use of undeclared identifier 'j' printf("i = (%i) j = (%i)\n", i , j); ^ fatal error: too many errors emitted, stopping now [-ferror-limit=] 2 errors generated. make: *** [: runoff] Error 1 "
I tried to rename the variable, or switch it to see what the problem is. I'm doing CS50 which is an introductional course to programming, so I'm not too sure what to do at this point. All help is appreciciated.
CodePudding user response:
If you used less erratic indentation, you'd realize that only preferences[i][j] = rank;
is in the body of the for (int j = 1; …)
loop. You need to use braces around at least the two printf()
statements (and the assignment) to group them into the loop body; the loop body should probably include the return
statement too.
You have:
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i )
{
if (strcmp(candidates[i].name, name)==0)
{
for (int j = 1; j <candidate_count; j )
preferences[i][j] = rank;
printf("i = (%i) j = (%i)\n", i , j);
printf("prefenrences[i][j], (%i)(%i)\n", preferences[i][j]);
return true;
}
}
printf("text");
return false;
}
You probably need:
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i )
{
if (strcmp(candidates[i].name, name) == 0)
{
for (int j = 1; j < candidate_count; j )
{
preferences[i][j] = rank;
printf("i = (%i) j = (%i)\n", i , j);
printf("prefenrences[i][j], (%i)\n", preferences[i][j]);
return true;
}
}
}
printf("text\n");
return false;
}
Note that I've corrected the second printf()
so that there is only one %i
conversion specification since you only pass one value to be formatted.