Python has an interesting for
statement which lets you specify an else
clause.
In a construct like this one:
for i in foo:
if
I am not aware of an elegant way to accomplish this in C/C++ (not involving a flag variable). The suggested other options are much more horrible than that...
To answer @Kerrek SB about real life usages, I found a few in my code (simplified snippets)
Example 1: typical find/fail
for item in elements:
if condition(item):
do_stuff(item)
break
else: #for else
raise Exception("No valid item in elements")
Example 2: limited number of attempts
for retrynum in range(max_retries):
try:
attempt_operation()
except SomeException:
continue
else:
break
else: #for else
raise Exception("Operation failed {} times".format(max_retries))