Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ for loop with existing start value

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?

like image 438
eje211 Avatar asked Sep 15 '25 12:09

eje211


1 Answers

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.

like image 118
Deepu Avatar answered Sep 18 '25 05:09

Deepu