2
for (int a = 0, int x = 1; a < 2; a++, x++)
{
  // Body
}

When I do this, it shows me an error on that line at the part when I declare x.

The error is:

error: expected identifier or '('
        for (int a = 0, int x = 1; a < 2 && x < 3; a++, x++)

Please note that this was the first time I ever declared x.

This problem is related to cs50's filter.

I tried googling to see if the code itself was incorrect but all the example were like mine.

I tried replacing the , with ; but that just made another error saying it was expecting an expression at the very same place.

I also tried remove the int from x and declaring it at the start of the function but that also was an error saying it was shadowing a local variable.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

2 Answers2

4

A for loop is a convenience construct around the more basic while loop to help programmers associate the variables being used and to constrain the scope of those used in the initializer clause. The initializer clause needs to be a valid initializer statment (or empty). Multiple definitions with type specifications separated by a comma is not a valid init statement.

int a = 0, int x = 1;

would need to be

int a = 0, x = 1;

And if variables with different types would be needed, you could use a while loop:

{ // scope limiter
    int a = 0;
    double x = 1.0;
    while(a < 2) {
        // Body
        ++a;
        ++x;
    }
}

... or a combination of the two:

{ // scope limiter
    double x = 1.0;
    for(int a = 0; a < 2; ++a, ++x) {
        // Body
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

Change to

for (int a = 0, x = 1; a < 2; a++, x++)

If you want multiple variables of different type, declare them before the loop.

klutt
  • 30,332
  • 17
  • 55
  • 95