Konrad Eisele
Konrad Eisele

Reputation: 3194

auto declare variable inside condition expression of while in c++

I have a code that uses a while statement. Inside the conditional expression I do a lookup. At the same time the conditional expression checks the return value:

#include <map>

struct a {
    a *up;
    std::map<int,int> tbl;
};

void p(a *_a, int id) {
    decltype(_a->tbl)::iterator i;
    while (_a && (i = _a->tbl.find(id)) != _a->tbl.end()) {
        i->second += 1;
        _a = _a->up;
    }
}

int main(int arc, char **argv) {
    a _a1{0,{{0,10},{1,10}}};
    a _a0{&_a1,{{2,11},{3,11}}};
    p(&_a0, 0);
    return 0;
}

However I would like to get rid of the explicit declaration of i. I would like to use auto. In pseudocode:

...
void p(a *_a, int id) {
    while (_a && ((auto i = _a->tbl.find(id))) != _a->tbl.end()) {
        i->second += 1;
        _a = _a->up;
    }
}
...

Is there a construct in c++11/14/17 that supports this kind of declarations inside an expression? Not only while(auto i = 1) {...} style declarations? Maybe there are some new features that allow this?

Upvotes: 0

Views: 1418

Answers (1)

Nelfeal
Nelfeal

Reputation: 13269

How about separating the two conditions? The main one for the loop to continue is _a, and the secondary one (which may always be true) is _a->tbl.find(id) != _a->tbl.end(). Return on its negation:

void p(a *_a, int id) {
    while (_a) {
        auto i = _a->tbl.find(id);
        if (i == _a->tbl.end()) {
            return;
        }
        i->second += 1;
        _a = _a->up;
    }
}

Upvotes: 3

Related Questions