Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to the "for ... else" Python loop in C++?

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?

like image 848
Delgan Avatar asked Jul 11 '14 08:07

Delgan


People also ask

Is there a for Else loop in C?

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.

Is there else for for loop in Python?

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.

Can a for loop have an else statement?

'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.


1 Answers

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: ... 
like image 75
ifyalciner Avatar answered Oct 03 '22 22:10

ifyalciner