Skip to content

Instantly share code, notes, and snippets.

@bfroehle
Last active December 22, 2015 01:08
Show Gist options
  • Save bfroehle/6393876 to your computer and use it in GitHub Desktop.
Save bfroehle/6393876 to your computer and use it in GitHub Desktop.
Emulate Python's for-else construct in C++.
#include <iostream>
// Emulate the for-else Python construct in C++.
// http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
int main() {
for (int n = 2; n < 10; n++) {
bool success = true;
for (int x = 2; x < n || (success = false); x++) {
if (n % x == 0) {
std::cout << n << " equals " << x << " * " << n / x << "\n";
break;
}
}
if (!success) {
// loop fell through without finding a factor
std::cout << n << " is a prime number\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment