Reputation: 153
I have a while loop, and I want some line of code to be run if the while loop runs at least once. If the while loop does not run, I want to skip this line of code.
while(condition) {
doSomething();
}
doSomethingElse();
/* Only run doSomethingElse() if the while loop ran
at least once */
I could set a bool to false before it runs, and set it to true when it runs, but to me it feels a little messy. Also, this while loop is inside a function that can run up to 10^6 times, and it has time constraints, so I want it to run as efficiently as possible. Is there any way to do this?
*note: Do not confuse this with a do-while loop which runs at least once no matter what. I want a line of code that runs only if the while loop is run at least once.
Upvotes: 1
Views: 677
Reputation:
int count=0;
while(condition) {
doSomething();
count=count+1;
}if(count >=1) {
// Enter the block of code that you want to run at least once }
Upvotes: 0
Reputation: 310990
It seems you mean
if ( condition )
{
while(condition) {
doSomething();
}
doSomethingElse();
}
Or
if ( bool b = condition )
{
while( b) {
doSomething();
b = condition;
}
doSomethingElse();
}
or
if ( condition )
{
do {
doSomething();
} while ( condition );
doSomethingElse();
}
Upvotes: 5