Is there an equivalent to the "for ... else" Python loop in C++? - Stack Overflow
While loop with else statement - C++ Forum
Coding for 30 years: Just realized "else if" is not a language construct in C/C++ and Javascript
When to use If/Else, and when to use Switch?
Videos
If you don't mind using goto, it can also be achieved in following way. This solutions saves from an extra if check and higher scope flag to track if loop is properly completed.
for(int i = 0; i < foo; i++)
if(bar(i))
goto m_label;
baz();
m_label:
...
A simpler way to express your actual logic is with std::none_of:
if (std::none_of(std::begin(foo), std::end(foo), bar))
baz();
If the range proposal for C++17 gets accepted, hopefully this will simplify to:
if (std::none_of(foo, bar)) baz();
Edit: I messed up the title. Should read "else if" is not a keyword.
Original:
Because I first learned Basic's "elseif" keyword, I always assumed C, C#, Javascript's "else if" was just a variant of Basic's keyword with an extra space.
Nope.
Those languages only have if/else. There is no language keyword elseif or "else if".
The reason they don't need it is because the "else" is designed to run whatever statement or compound statement that is after the else. And in the case we care about, "else if(){}" the "if() {}" is treated as a compound statement. It's no different than log(100); or { if(isHundred ) log(100); else logNan();}
So while C/C++, Javascript can "else if" it's really just an else and an if. "else if" is nothing special.
Basic and Python lua require elseif because they don't have the single statement or compound statement rule and every else must be matched to an endif or end. Edit: Python uses elif to reduce indentation.
Anyway, apologies if this was obvious. It's really a distinction without a difference but I guess it goes to show that we are always learning and new concepts are always clicking even after decades of using a language.
Is there a consensus on where it's acceptable to just use switch statements? Like a certain number of conditions?
Thanks
Obviously...
if (map.empty())
{
// do stuff if map is empty
}
else for (auto it = map.begin(); it != map.end(); ++it)
{
// do iteration on stuff if it is not
}
By the way, since we are talking C++11 here, you can use this syntax:
if (map.empty())
{
// do stuff if map is empty
}
else for (auto it : map)
{
// do iteration on stuff if it is not
}
If you want more crazy control flow in C++, you can write it in C++11:
template<class R>bool empty(R const& r)
{
using std::begin; using std::end;
return begin(r)==end(r);
}
template<class Container, class Body, class Else>
void for_else( Container&& c, Body&& b, Else&& e ) {
if (empty(c)) std::forward<Else>(e)();
else for ( auto&& i : std::forward<Container>(c) )
b(std::forward<decltype(i)>(i));
}
for_else( map, & {
// loop body
}, [&]{
// else body
});
but I'd advise against it.