具有现有起始值的C / C ++ for循环

时间:2013-06-01 04:27:20

标签: c++ c variables for-loop

这是一个C / C ++ for循环:

int i;
for (i = myVar; i != someCondition(); i++)
  doSomething();
// i is now myVar plus the number of iterations until someCondition

我最近不得不使用这样的循环。我需要保留i的值,因为我想知道当i的返回值变为真时someCondition()是什么。 i的起始值为myVar,没有其他原因存在。那么想要做的是:

for (myVar; myVar != someCondition(); myVar++)
  doSomething();
// myVar is now myVar + the number of iterations.

这对我来说更有意义。当myVar正是我需要的时候,我不明白为什么我必须使用一个全新的变量。但这不是有效的代码。有没有办法为这种情况创建一个全新的变量?

3 个答案:

答案 0 :(得分:6)

你需要的是,

for( ; myVar != someCondition(); myVar++)
       doSomething();

但你声明以下循环不正确是错误的,

for (myVar; myVar != someCondition(); myVar++)
  doSomething();

上述代码在C中也可以正常工作。

答案 1 :(得分:2)

我认为这就是你所追求的:

for ( ; myVar != someCondition(); myVar++)
    doSomething();

答案 2 :(得分:0)

我觉得while循环更接近你的意图。事实上,你正在做while someCondition() true的事情,增加myVar是一个副作用。

while(myvar != someCondition()) {
 doSomething();
 myVar++;
}

要明确:陈述是等同的。我只是在倡导我认为更惯用的代码。

你甚至可以使用do / while循环,但它对我来说有点不合时宜。下面你会发现三个例子;他们都这样做,但感觉不同。随便挑选!

#include<iostream>

int someCondition() {
  return 10;
}

void doSomething(int myVar) {
  std::cout<<"... I'm doing something with myVar = "<<myVar<<std::endl;
}

int using_for() {
  int myVar = 7;
  for( ; myVar!=someCondition(); myVar++) {
    doSomething(myVar);
  }
  return myVar;
}

int using_while() {
  int myVar = 7;
  while(myVar != someCondition()) {
    doSomething(myVar);
    myVar++;
  }
  return myVar;
}

int using_do() {
  int myVar = 7;
  do {
    doSomething(myVar);
  } while(++myVar != someCondition());
  return myVar;

}

int main() {
  std::cout<<"using for: "<<using_for()<<std::endl;
  std::cout<<"using while: "<<using_while()<<std::endl;
  std::cout<<"using do/while: "<<using_do()<<std::endl;

}

输出:

... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using for: 10
... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using while: 10
... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using do/while: 10