bodacydo bodacydo - 2 months ago 8
C Question

How to initialize several variables in a for (;;) loop in C?

I thought one could initialize 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 initialize variables of different types in a
for
loop?

Answer

You can (but generally shouldn't) use an 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.