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):
#include <vector>
#include <iostream>
using namespace std;
#define FOR_EACH(e, c, b) auto e = c.begin(); for (; e != c.end(); ++e) {b} if (e == c.end()) {}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
FOR_EACH(x, v, {
if (*x == 2) {
break;
}
cout << "x = " << *x << " ";
})
else {
cout << "else";
}
return 0;
}
This should output x = 1 else
.
If you change if (*x == 2) {
to if (*x == 3) {
, the output should be x = 1 x = 2
.
If you don't like the fact that a variable is added in the current scope, you can change it slightly:
#define FOR_EACH(e, c, b, otherwise) {auto e = c.begin(); for (; e != c.end(); ++e) {b} if (e == c.end()) {} otherwise }
then use would be:
FOR_EACH(x, v, {
if (*x == 2) {
break;
}
cout << "x = " << *x << " ";
},
else {
cout << "else";
})
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".
find()
is a classic example where this conctruct is used. – Voicelessreturn
, not abreak
, and then it does skip the code immediately following the loop. – Malchyif (c)
,while (c)
andfor (...; c; ...)
evaluatec
, but at present only the first one lets you access the result of this expression. The other two are throwing away this information, which violates the principle that you should not throw away results that were obtained as part of a computation. – Wallsnot break
statement-block has the benefit of using existing keywords, for better backwards compatibility (and being strongly indicative of the conditions under which it runs). In C++ the use ofelse
for this would conflict with existing code a laif (...) for (...) ...; else ...
. – Matriarchybreak
byreturn
. – Occasion