0

The following code will not compile:

#include <iostream>

int main(){

    for (int i = 0, double j = 0; i < 10; ++i, j+=.1){
        std::cout << i << " " << j << '\n';
    }

    return 0;
}

Is it possible to initialize two different types, or do I need to create a struct/pair/etc?

Trevor Hickey
  • 31,728
  • 22
  • 131
  • 236

5 Answers5

9

No.

But you can define an anonymous struct right there as:

for (struct { int i; double j; } x = {0,0};  x.i < 10; ++x.i, x.j+=.1)
{
    std::cout << x.i << " " << x.j << '\n';
}

See the initialization part:

struct { int i; double j; } x = {0,0};

It defines an anonymous struct, then creates an object x and initializes it with {0,0} which initializes both members i and j with 0.

Nawaz
  • 327,095
  • 105
  • 629
  • 812
  • It does not compile for me on VC++ :O, does it for you? – Saqlain Apr 03 '13 at 18:36
  • @Saqlain: Yes. [See yourself here](http://coliru.stacked-crooked.com/view?id=6bd36fc4b91846b1084d84207525b5a3-61c3814520a8d4318f681038dc4b4da7). – Nawaz Apr 03 '13 at 18:38
  • 1
    http://stackoverflow.com/a/889001/34509 – Johannes Schaub - litb Apr 03 '13 at 18:40
  • On VS 2005 i get below error with above code error C2332: 'struct' : missing tag name error C2143: syntax error : missing ')' before '{' warning C4094: untagged 'struct' declared no symbols error C2059: syntax error : 'empty declaration' error C2143: syntax error : missing ';' before ')' error C2143: syntax error : missing ';' before ')' error C2065: 'x' : undeclared identifier error C2059: syntax error : '{' error C2143: syntax error : missing ';' before '{' error C2143: syntax error : missing ';' before '}' – Saqlain Apr 03 '13 at 18:42
  • @Saqlain: That means MSVC2005 has bug. – Nawaz Apr 03 '13 at 18:42
  • Yep, that can be true! – Saqlain Apr 03 '13 at 18:43
2

Not possible, but there is way:

double var1;
int var2;
for (var2 = 0,var1 = 0.0; var2 < 12; var2++){}

If you want to limit scope of f and i then enclose them in {}, just like

{
    double var1;
    int var2;
    for (var2 = 0,var1 = 0.0; var2 < 12; var2++){}
}
Saqlain
  • 15,990
  • 4
  • 25
  • 33
1

No, you can't. You can have multiple variables, but they have to be the same type.

Luchian Grigore
  • 236,802
  • 53
  • 428
  • 594
0

They have to be the same type, but you can use structs to bypass that.

for (struct {int j; char i;} loop = {0, 'e'}; loop.i < 33; ++loop.j, ++loop.i)
{
    std::cout << loop.i << '\n';
}
frickskit
  • 614
  • 1
  • 8
  • 18
0

Can do the following

#include<cstdlib>
#include<iostream>

int main(int argc, char *argv[]){

    int i; double j;
    for(i = 0, j = 0; i < 10; ++i, j+= .1){
        std::cout << i << " " << j << '\n';
    }


    return EXIT_SUCCESS;
}
Mushy
  • 2,225
  • 9
  • 30
  • 50