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
?
Conditional Statements – if else, for and while loop in CThis involves using some operations called Relational Operators and conditional statements called if-else and loops. We use fundamental operators to compare two values in our C programs.
Python allows the else keyword to be used with the for and while loops too. The else block appears after the body of the loop. The statements in the else block will be executed after all iterations are completed.
'else' Clause in 'for' LoopLoop statements may have an else clause. It is executed when the for loop terminates through exhaustion of the iterable — but not when the loop is terminated by a break statement.
If doesn't mind using goto
also can be done in following way. This one saves from extra if
check and higher scope variable declaration.
for(int i = 0; i < foo; i++) if(bar(i)) goto m_label; baz(); m_label: ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With