Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Counter Problem In For Loop

Tags:

c++

for-loop

Why is this not valid

for( int i = 0, int x = 0; some condition; ++i, ++x )

and this is

int i, x;
for( i = 0, x = 0; some condition; ++i, ++x )

Thanks

like image 889
Thomas Avatar asked Sep 05 '25 09:09

Thomas


2 Answers

when you need to declare two variables of different types, it can't be done by one declaration

Hackety hack hack:

for (struct {int i; char c;} loop = {0, 'a'}; loop.i < 26; ++loop.i, ++loop.c)
{
    std::cout << loop.c << '\n';
}

;-)

like image 92
fredoverflow Avatar answered Sep 08 '25 06:09

fredoverflow


this works:

for( int i = 0, x = 0; some condition; ++i, ++x )

it's a variable declaration:

int i, j; // correct
int i, int j; // wrong, must not repeat type
like image 32
sergiom Avatar answered Sep 08 '25 05:09

sergiom