如何在 C 中的 for (;;) 循环中声明多个变量? [英] How do I declare several variables in a for (;;) loop in C?
问题描述
我认为可以在 for
循环中声明多个变量:
I thought one could declare 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' 之前的预期未限定 id
error: expected unqualified-id before 'char'
在 for
循环中不能声明不同类型的变量是真的吗?
Is it really true that you can't declare 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 addresses the problem with structured bindings:
for ( auto [ i, status ] = std::tuple{ 0, ""s }; status != "done"; ++ i )
这篇关于如何在 C 中的 for (;;) 循环中声明多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!