I write this code and declare the c variable in if chains, but the compiler gives me an error says you did not declare this variable. `
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int k = atoi(argv[1]);
printf ("%i\n", k);
string p = get_string ("Plaintext: \n");
for (int i = 0; i < strlen(p); i )
{
if (isalpha(p[i]))
{
if (islower(p[i]))
{
char c = (((p[i] - 97) k) % 26) 97;
return 0;
}
else if (isupper(p[i]))
{
char c = (((p[i] - 65) k) % 26) 65;
return 0;
}
else{
char c = (((p[i] - 65) k) % 26) 65;
}
p[i] = c;
}
}
printf ("%s\n", p);
return 0;
}
` test2.c: In function ‘main’: test2.c:34:20: error: ‘c’ undeclared (first use in this function) 34 | p[i] = c; | ^ test2.c:34:20: note: each undeclared identifier is reported only once for each function it appears in
CodePudding user response:
'If' block itself is a scope, and you define a scope and the variables are only accessible inside the scope, not outside, and not at the boundary either.
For sure, the c variable should be declared outside the For loop:
char c = ' ';
for ...
CodePudding user response:
The error would occur at following line:
p[i] = c;
It is because c
is local scope at the following line:
if (islower(p[i]))
{
char c = (((p[i] - 97) k) % 26) 97;
return 0;
}
and
{
char c = (((p[i] - 65) k) % 26) 65;
return 0;
}
and
else{
char c = (((p[i] - 65) k) % 26) 65;
}
Local scope means that it will be released after exit the }
.
Additionally, after first 2 condition of if
, else if
, there is also return
after define value to c
. If so, the API will return immediate and c
is not used at any line because the assignment p[i] = c;
will not execute.