如何在C中的for(;;)循环中声明几个变量? [英] How do I declare several variables in a for (;;) loop in C?

查看:387
本文介绍了如何在C中的for(;;)循环中声明几个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为可以在 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之前的预期unqualified-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 )
    { ... }

这几乎足以真正使用。

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

C++17 addresses the problem with structured bindings:

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

这篇关于如何在C中的for(;;)循环中声明几个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆