0

For the Caesar pset, I am having trouble trying to fixing an expected expression error.

for (int i = 0; i < int n = strlen(argv[1]); i++)
{
    printf("test");
}

The condition inside the for-loop will work if it's outside it like so:

int n = strlen(argv[1]);
for (int i = 0; i < n; i++)
{
    printf("test");
}

Could anyone explain why this works but the other for loop doesn't?

1

An expression is something that returns a value, like strlen(argv[1]) or i++. This int n = strlen(argv[1]) is a declaration or assigment operator.

In a for statement, only the first argument allows initialization/assignment.

Program would also compile like so:

for (int i = 0, n = strlen(argv[1]); i < n; i++)

Similar to this example in the lecture:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    string s = get_string("Input: ");
    printf("Output:\n");
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        printf("%c\n", s[i]);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .