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 he gives an error, means that this is not allowed. Any solution for this?

+5
source share
7 answers

Do not write such code. This is a speed code that someone will once read and set off Whoa! and lose 5 minutes of his life, trying to understand why you did it. Within 5 minutes he will never return, you will be obliged to him for a good reason.

If squeezing the result volume is really important, use an extra set of curly braces:

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

, , :

void printPowersOfTwo(int from, int to)
+21

:

int loop=0, long result = 1;

- .

:

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

+6

, (.. int int* , int a long).

+3

++. .

, , struct ,

struct local {int loop; long result; };

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

ideone: http://www.ideone.com/ELT4a


struct for, ,

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

: http://www.ideone.com/X1MdC

+3

- , . , , , . "loop" , "i", <= in a for < , .

long result=1;
for (int i=0; i<11; i++)
{
  std::cout << "2^" << i << " = " << result << std::endl;
  result *= 2;
}
+3

-

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

++;

+2

, .

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

As a warning, if you call this twice, this can be a problem.

I recently deflated it

for (double tempTemp = 0.0,i=0;tempTemp >=targetTemp;i++)
{
  Sleep(100);
  deviceSafeCall(IL_GetFloat(myHandle,L"SensorTemperature",&tempTemp));
  cout << ".";
  static int fancy = 0;
  if (++fancy%10==0)
  {
      cout <<tempTemp <<endl;
  }
}
0
source

All Articles