At the moment, I am having to write out multiple for-loops
which all do the same task, with the differences being in the initialization, condition, and the de/incrementation within the for-loops
themselves.
Here is an example of something similar I have so far:
if(some_bool_condition)
{
for(int i = 0; i < 5; i++)
{
// do something
}
}
else
{
for(int i = 10; i >= 5; i--)
{
// do same thing
}
}
Is there a trick or technique I can use to merge these for-loops
together?
int start = 0; // or some other value
int end = 5; // ditto
int delta = 1; // 1 or -1
for ( int i = start; i != end; i += delta )
{
// do something
}
Of course the delta has to be choosen carefully so that i
actually reaches end
exactly.
Make do someting be a function. Pass the start value, test, and increment/decrement value as arguments. Do the for loop in the function.
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.