I have a loop with an index. But the index jumps up and down from time to time, so a for loop is out of the question. But I still need the index. I just don't like the idea of having a temporary index in my function which I am only using for one loop. e.g.
...
int i = 0;
while( i < something)
{
if(a)
i :
else
i--:
}
...
Can I make i temporary for the loop? Maybe something like this?
...
temporary (int i = 0)
{
while( i < something)
{
if(a)
i :
else
i--:
}
}
...
CodePudding user response:
You can use the for loop
in order to achieve this. the variable i will live only inside the for loop
scope.
for (int i = 0; i < something;;)
{
if(a)
i :
else
i--:
}
}
CodePudding user response:
You can limit the range of a variable by enclosing its declaration and its use within curly braces. It looks a litte bit strange, but it works fine.
Then your i
variable can't be accessed outside of this scope as shown below (you will get a compilation error) :
MyMethod()
{
// ... lots of code here
{
int i=0;
while( i < something)
{
if(a)
i ;
else
i--;
}
i--; // ok
}
i--; // error : The name 'i' does not exist in the current context
// ... some more code here
}