Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed declaration in a for loop

I want to write a for loop as shown below; in the initialization section, I want to declare variables of different types:

    for (int loop=0, long result = 1; loop <= 10 ; loop++, result *= 2 )
    {
        cout << "2^"<<loop<<"=" << result<<endl;
    }

But it is giving error, means it's not allowed. Any solution for that?

like image 455
Nawaz Avatar asked Dec 26 '10 06:12

Nawaz


3 Answers

Don't write code like this. It is speed-bump code, somebody will read this some day and go Whoa! and lose 5 minutes of his life trying to figure out why you did this. That's 5 minutes he'll never get back, you'll owe him for no good reason.

If constricting the scope of result is really that important then use an extra set of braces:

{
    long result = 1;
    for (int loop = 0; loop <= 10; loop++)
    {
        cout << "2^" << loop << "=" << result << endl;
        result *= 2;
    }
}

Now put this on top and you'll have written not just readable code but re-usable code:

void printPowersOfTwo(int from, int to)
like image 120
Hans Passant Avatar answered Oct 15 '22 08:10

Hans Passant


it is as if you tried:

int loop=0, long result = 1;

anywhere else.

you can do this:

for (struct { int loop; long result; } vars = { 0, 1};

but dont

like image 6
Anycorn Avatar answered Oct 15 '22 09:10

Anycorn


You can declare multiple variables in a for loop declaration part as long as they are of a single base type (i.e. you can declare an int and an int* in a single declaration, but not an int and a long).

like image 3
mmx Avatar answered Oct 15 '22 08:10

mmx