How do I declare several variables in a for (;;) loop in C? How do I declare several variables in a for (;;) loop in C? c c

How do I declare several variables in a for (;;) loop in C?


You can (but generally shouldn't) use a local struct type.

for ( struct { int i; char* ptr; } loopy = { 0, bam };      loopy.i < 10 && * loopy.ptr != 0;      ++ loopy.i, ++ loopy.ptr )    { ... }

Since C++11, you can initialize the individual parts more elegantly, as long as they don't depend on a local variable:

for ( struct { int i = 0; std::string status; } loop;      loop.status != "done"; ++ loop.i )    { ... }

This is just almost readable enough to really use.


C++17 addresses the problem with structured bindings:

for ( auto [ i, status ] = std::tuple{ 0, ""s }; status != "done"; ++ i )


It's true that you can't simultaneously declare and initialize declarators of different types. But this isn't specific to for loops. You'll get an error if you do:

int i = 0, char *ptr = bam;

too. The first clause of a for loop can be (C99 §6.8.5.3) "a declaration" or a "void expression". Note that you can do:

int i = 0, *j = NULL;for(int i = 0, *j = NULL;;){}

because i and *j are both of type int. The exact syntax for a declaration is given in §6.7


If you really need the variables to stay in the scope of the loop you could write

{ char* ptr = bam; for (int i = 0; i < 10; i++) { ... } }

It's a bit ugly, but works.