Here's a C/C++ for loop:
int i;
for (i = myVar; i != someCondition(); i++)
doSomething();
// i is now myVar plus the number of iterations until someCondition
I recently had to use a loop like this. I needed to keep the value of i
because I wanted to know what i
was when the return value of someCondition()
became true. And the start value of i
was myVar
which had no further reason of existing. So what wanted to do was:
for (myVar; myVar != someCondition(); myVar++)
doSomething();
// myVar is now myVar + the number of iterations.
This made a lot more sense to me. I didn't see why I had to use a whole new variable when myVar
was just what I needed. But this is not valid code. Is there a way around creating a whole new variable for this situation?
What you need is,
for( ; myVar != someCondition(); myVar++)
doSomething();
But you statement about the following loop being incorrect is wrong,
for (myVar; myVar != someCondition(); myVar++)
doSomething();
The above code will also work fine in C.
I think this is what you're after:
for ( ; myVar != someCondition(); myVar++)
doSomething();
I feel that a while
loop more closely resembles your intentions. Indeed, you are doing something while
someCondition()
is true
, and increasing myVar
is a side effect.
while(myvar != someCondition()) {
doSomething();
myVar++;
}
To be clear: the statements are equivalent. I am just advocating for what I believe to be more idiomatic code.
You could even use a do
/ while
loop, but it somewhat does not feel idiomatic to me. Below you will find three examples; they all do the same, but feel different. Take your pick!
#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;
}
Output:
... 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.