cloopsfor-loopdeclaration

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


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?


Solution

  • 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 )
        { ... }
    

    (Bonus C++ answers)

    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:

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