Created
March 23, 2020 16:39
-
-
Save mtao/50821422316eec277e31b02ebf9aa2b3 to your computer and use it in GitHub Desktop.
three alternatives for breaking out of embedded for loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
int main(int argc, char* argv[]) { | |
{ | |
// a typical embedded loop check can require a check for success and | |
// multiple checks to unroll | |
bool success = false; | |
int i = 0, j = 0; | |
for (i = 0; i < 50; ++i) { | |
for (j = 0; j < 50; ++j) { | |
// check if we succeed at some task using i and j | |
success = i * j > 48 * 48; | |
// if we succeed then break out of j loop | |
if (success) break; | |
} | |
// if we succeed then break out of i loop | |
if (success) break; | |
} | |
// congratulate ourselves for our great success | |
if (success) { | |
std::cout << i << "," << j << std::endl; | |
} | |
} | |
{ | |
// a goto can do this pretty easily; goto is also relatively safe | |
int i = 0, j = 0; | |
for (i = 0; i < 50; ++i) { | |
for (j = 0; j < 50; ++j) { | |
// check if we succeed at some task using i and j | |
if (i * j > 48 * 48) { | |
goto success; | |
} | |
} | |
} | |
goto fail; | |
success: | |
// congratulate ourselves for our great success | |
std::cout << i << "," << j << std::endl; | |
// failure case requires this :; to have a nonempty line afterwards | |
fail:; | |
} | |
{ | |
// an anonymous lambda function lets us do this in a nicely scoped way | |
// that is perhaps more readable. the lambda with return lets us define | |
// the scope to break out of | |
// We can use C++ if statements with initalizers too :) | |
if ( | |
int i = 0, j = 0; [&i, &j]() -> bool { | |
for (i = 0; i < 50; ++i) { | |
for (j = 0; j < 50; ++j) { | |
// check if we succeed at some task using i and j | |
if (i * j > 48 * 48) { | |
return true; | |
} | |
} | |
} | |
return false; | |
}()) { | |
// congratulate ourselves for our great success | |
std::cout << i << "," << j << std::endl; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment