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

bodacydo picture bodacydo · Jul 28, 2010 · Viewed 48k times · Source

I thought one could declare several variables in a for loop:

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

But I just found out that this is not possible. GCC gives the following error:

error: expected unqualified-id before 'char'

Is it really true that you can't declare variables of different types in a for loop?

Answer

Potatoswatter picture Potatoswatter · Jul 28, 2010

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 )