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?
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)
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
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With