如何初始化一个为(;;)在空调回路几个变量? [英] How to initialize several variables in a for (;;) loop in C?
本文介绍了如何初始化一个为(;;)在空调回路几个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为人们可以在为
环路初始化几个变量:
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:
error: expected unqualified-id before 'char'
难道真的,你不能在为
环路初始化不同类型的变量?
Is it really true that you can't initialize variables of different types in a for
loop?
推荐答案
您可以(但一般不宜)使用当地的结构类型。
You can (but generally shouldn't) use an 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.
这篇关于如何初始化一个为(;;)在空调回路几个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文