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:

using namespace std::literals::string_literals;

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

Leave a Comment