如何在C中的for(;;)循环中初始化几个变量? [英] How do I initialize several variables in a for (;;) loop in C?
问题描述
我以为可以在for
循环中初始化几个变量:
I thought one could initialize several variables in a for
loop:
for (int i = 0, char* ptr = bam; i < 10; i++) { ... }
但是我刚刚发现这是不可能的. GCC出现以下错误:
But I just found out that this is not possible. GCC gives the following error:
错误:"char"之前的预期unqualified-id
error: expected unqualified-id before 'char'
真的不能在for
循环中初始化不同类型的变量吗?
Is it really true that you can't initialize variables of different types in a for
loop?
推荐答案
您可以(但通常不应该)使用本地结构类型.
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 )
{ ... }
这几乎足以使人真正使用它.
This is just almost readable enough to really use.
C ++ 17计划解决结构化绑定的问题:
C++17 is scheduled to address the problem with structured bindings:
for ( auto [ i, status ] = { 0, ""s }; status != "done"; ++ i )
但是,详细的功能集和语法仍在不断变化.
However, the detailed feature set and syntax are still in flux.
这篇关于如何在C中的for(;;)循环中初始化几个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!