c++ Warning: Clang-Tidy: Repeated branch in conditional chain
Asked Answered
G

1

7

Can you help me how to avoid the warning in this code ...

Warning: Clang-Tidy: Repeated branch in conditional chain

HubInterface *getFreeHub() {
        HubInterface *freeHub = nullptr;
        while (freeHub == nullptr) {
            for (auto hub : this->getHubList()) {
                if (freeHub == nullptr) {
                    freeHub = hub;
                } else if (hub->getStatus() == STATUS_READY &&
                           hub->getBusyNodes().size() < freeHub->getBusyNodes().size()) {
                    freeHub = hub;
                }
            }
            sleep(5);
        }
        return freeHub;
    }

Warning provided by CLion IDE

Gotham answered 29/2, 2020 at 13:20 Comment(0)
L
12

The warning is about the fact that you are doing the same thing in your if and else if branches, which is freeHub = hub;

if (freeHub == nullptr) {
    freeHub = hub;
} else if (hub->getStatus() == STATUS_READY &&
           hub->getBusyNodes().size() < freeHub->getBusyNodes().size()) {
    freeHub = hub; // same as above, what is the point?
}

I suppose you could rewrite it as a single condition but it's getting a bit scary:

if (freeHub == nullptr ||
    (hub->getStatus() == STATUS_READY &&
     hub->getBusyNodes().size() < freeHub->getBusyNodes().size())) {
    freeHub = hub;
}
Liberticide answered 29/2, 2020 at 14:1 Comment(3)
there ara many hubs, I need a hub with the status of "READY" and the least number of occupied nodes...Gotham
@mat.twg, I understand, but according to your code you don't check those conditions when freeHub is null, right?Liberticide
Thank you very much! I was updated code, now all seems ok... also additional conditions added.Gotham

© 2022 - 2024 — McMap. All rights reserved.