Python has an interesting for
statement which lets you specify an else
clause.
In a construct like this one:
for i in foo:
if
You can use for-else almost like in Python by defining two macros:
#define BREAK {CONTINUETOELSE = false; break;}
#define FORWITHELSE(x, y) {bool CONTINUETOELSE = true; x if(!CONTINUETOELSE){} y}
Now you put the for
and the else
inside the FORWITHELSE
macro separated by a comma and use BREAK
instead of break
. Here is an example:
FORWITHELSE(
for(int i = 0; i < foo; i++){
if(bar(i)){
BREAK;
}
},
else{
baz();
}
)
There are two things you need to remember: to put a comma before the else
and to use BREAK
instead of break
.
Yes you can achieve the same effect by:
auto it = std::begin(foo);
for (; it != std::end(foo); ++it)
if(bar(*it))
break;
if(it == std::end(foo))
baz();