Python has an interesting for
statement which lets you specify an else
clause.
In a construct like this one:
for i in foo:
if bar(i):
break
else:
baz()
the else
clause is executed after the for
, but only if the for
terminates normally (not by a break
).
I wondered if there was an equivalent in C++? Can I use for ... else
?
You can use for-else almost like in Python by defining two macros:
Now you put the
for
and theelse
inside theFORWITHELSE
macro separated by a comma and useBREAK
instead ofbreak
. Here is an example:There are two things you need to remember: to put a comma before the
else
and to useBREAK
instead ofbreak
.This is my rough implementation in C++:
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
Example 2: limited number of attempts
There probably isn't a single solution that fits best all problems. In my case a flag variable and a range-based
for
loop with anauto
specifier worked best. Here's an equivalent of the code in question:It is less typing than using iterators. Especially, if you use the
for
loop to initialize a variable, you may use that instead of the boolean flag.Thanks to
auto
typing it is better thanstd::none_of
, if you want to inline the condition rather than callbar()
(and if you are not using C++14).I had a situation where both conditions occurred, the code looked something like this:
No need for iterators here, because
v
indicates whetherbreak
occurred.Using
std::none_of
would require specifying the type ofsupport_edges[x]
elements explicitly in arguments of a lambda expression.Direct answer: no, you probably can't, or it is compiler-based, at best. BUT here's a hack of a macro that kind of works!
A few notes:
I usually program with Qt, so I'm used to having a foreach loop, and never have to deal with iterators directly.
I tested this with Qt's compiler (v 5.4.2) but it should work. This is gross for several reasons, but generally does what you'd want. I don't condone coding like this, but there's no reason it shouldn't work as long as you're careful with the syntax.
There is no such language construct in C++, but, thanks to the "magic" of the preprocessor, you can make one for yourself. For example, something like this (C++11):
This should output
x = 1 else
.If you change
if (*x == 2) {
toif (*x == 3) {
, the output should bex = 1 x = 2
.If you don't like the fact that a variable is added in the current scope, you can change it slightly:
then use would be:
It's not perfect, of course, but, if used with care, will save you some amount of typing and, if used a lot, would become a part of the project's "vocabulary".