1

I'm trying to declare and initialize variables of different type inside a for-scope. Something like:

for (int i = 0, double u = 1; i < 10; ++i)
{...}

but the compiler (gcc) returns me an error.

I know that can perform initialization using the same type variables (example), but I don't know how is it possible do it with different ones.

Of course I can declare the variable outside the loop:

double u = 1;
for (int i = 0; i < 10; ++i)
{...}

but I'm looking for something clean because the variable u is used only inside the for-scope. So,

  • Can I do it?
  • If so, how can I?
Community
  • 1
  • 1
Blex
  • 156
  • 11
  • The cleanest way is probably to make it a new scope and put `u` outside of the loop. – chris Aug 04 '13 at 23:08
  • Got, the only (ugly) way is using structs. In this case the only thing I can do is declare `u` variable outside for-scope. – Blex Aug 04 '13 at 23:15

3 Answers3

2

Its not allowed to declare more then one type in a declration statement. The only way to contain u within the scope remotely close to the for loop would be something like that:

{
    double u = 1;
    for (int i = 0; i < 10; ++i)
    {
        //some code
    }
}// u's scope will end here
North-Pole
  • 610
  • 4
  • 13
1

Of course creating a new scope will do, but writing a function is more common way.

void foo()
{
    // So this function deals with loop and does something with 'u'.
    double u = 1;
    for (int i = 0; i < 10; ++i)
    { ... }
}

It is hard to say if you really need a function, but I believe it is a very clean and natural way.

Unforgiven
  • 125
  • 6
0

You have to think as if you are declaring these variables in another part of the code. You can declare as many variables as you want in the same line always if they share the type. You can declare: int a=3, b=3; But the ';' points the end of this type declaration. If you try to do: int a=3, double b= 3.4; As you wish the compiler translate that as a "double" declaration of the b variable. First the compiler recognize it as an int, but then you are specifying another type. Thats why you can't do that. If you try to do it as your compiler wish (type variable=value; another_type another_variable = another_value;) you'll break the for structure.