lebvlad lebvlad - 2 months ago 6
C Question

Expected identifier or '(' in simple for-loop in C

I write functiton, that check is string contain only letters or not. If i declare

n
outside the loop:

int n = strlen(str);
for (int i = 0; i < n; i++)


it has no errors and works great, but if i move
n
declaration inside:

for (int i = 0, int n = strlen(str); i < n; i++)


i have errors:

vigenere.c:71:21: error: expected identifier or '('
for (int i = 0, int n = strlen(str); i < n; i++)
^
vigenere.c:71:21: error: expected ';' in 'for' statement specifier
vigenere.c:71:21: error: expected expression
vigenere.c:71:46: error: use of undeclared identifier 'n'
for (int i = 0, int n = strlen(str); i < n; i++)
^
vigenere.c:71:47: error: expected ')'
for (int i = 0, int n = strlen(str); i < n; i++)
^
vigenere.c:71:9: note: to match this '('
for (int i = 0, int n = strlen(str); i < n; i++)
^
vigenere.c:71:49: error: use of undeclared identifier 'i'
for (int i = 0, int n = strlen(str); i < n; i++)
^
6 errors generated.


Why? I have the same loop in main() and it's work great.
Can somebody explain me the problem?
Thanks!

Fuction entirely:

int is_alpha_string(string str)
{
//for (int i = 0, int n = strlen(str); i < n; i++)
int n = strlen(str);
for (int i = 0; i < n; i++)
{
if (isalpha(str[i]) == 0)
{
return 0;
}
}

return 1;
}

Answer

You don't need the second int

for (int i = 0, **int** n = strlen(str); i < n; i++)

instead use

for (int i = 0, n = strlen(str); i < n; i++)