且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中的for(;;)循环中声明几个变量?

更新时间:2022-06-15 21:54:59

您可以(但通常不应该)使用本地结构类型。

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




自C ++ 11起,只要它们不依赖局部变量,就可以更优雅地初始化各个部分:


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

这几乎足以真正使用。

C ++ 17解决了 结构化绑定

C++17 addresses the problem with structured bindings:

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