是否有可能在c++的for循环的初始化体中声明两个不同类型的变量?

例如:

for(int i=0,j=0 ...

定义两个整数。我可以在初始化体中定义int和char吗?如何做到这一点呢?


当前回答

你不能在初始化时声明多个类型,但是你可以赋值给多个类型

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

只是在它们自己的范围内声明它们。

其他回答

没有-但技术上有一个变通的方法(不是说我真的会使用它,除非被迫):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

你不能在初始化时声明多个类型,但是你可以赋值给多个类型

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

只是在它们自己的范围内声明它们。

我认为最好的方法是西安的答案。

但是…


#嵌套for循环

这种方法很脏,但可以解决所有版本。

所以,我经常在宏函数中使用它。

for(int _int=0, /* make local variable */ \
    loopOnce=true; loopOnce==true; loopOnce=false)

    for(char _char=0; _char<3; _char++)
    {
        // do anything with
        // _int, _char
    }

额外的1。

它还可以用于声明局部变量和初始化全局变量。

float globalFloat;

for(int localInt=0, /* decalre local variable */ \
    _=1;_;_=0)

    for(globalFloat=2.f; localInt<3; localInt++) /* initialize global variable */
    {
        // do.
    }

额外的2。

很好的例子:使用宏函数。

(如果best方法不能使用,因为它是for-loop-宏)

#define for_two_decl(_decl_1, _decl_2, cond, incr) \
for(_decl_1, _=1;_;_=0)\
    for(_decl_2; (cond); (incr))


    for_two_decl(int i=0, char c=0, i<3, i++)
    {
        // your body with
        // i, c
    }

# if语句技巧

if (A* a=nullptr);
else
    for(...) // a is visible

如果你想初始化为0或nullptr,你可以使用这个技巧。

但我不建议这样做,因为很难阅读。

它看起来像虫子。

你也可以像下面这样在c++中使用。

int j=3;
int i=2;
for (; i<n && j<n ; j=j+2, i=i+2){
  // your code
}

定义一个宏:

#define FOR( typeX,x,valueX,  typeY,y,valueY,  condition, increments) typeX x; typeY y; for(x=valueX,y=valueY;condition;increments)

FOR(int,i,0,  int,f,0.0,  i < 5, i++)
{
  //...
}

只要记住,你的变量作用域也不会在for循环中。