Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unreachable-code-loop-increment warning rules

Consider the following code (clang). It has two identical loops explicitly terminated on the first iteration. One of them throws a warning (an error if -Wpedantic -Werror). The other does not. Trying to understand why. The code can be tested on Godbolt here


template <typename K, typename V>
int get(const std::map<K, V>& m) {
        for (const auto& [k, v]: m)
                return v.size(); // No warning
        return 0;
}

int main(int argc, char** argv) {
        std::map<char, std::string>m1 { {'A', "Alex"}, {'B', "Bob"}};
        std::cout << get(m1) << "\n";
        for (const auto& [k, v]: m1)
            return v.size(); // warning: loop will run at most once (loop increment never executed) [-Wunreachable-code-loop-increment] 
        return 0;
}

I expect a warning in both cases, although I don’t really see a value in this warning. If you are wondering, why – I wanted to implement something like:

if (mylist.begin() != mylist.end())
  return mylist.begin();

using a loop iterator.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The difference in behaviour seems to be a side-effect of making get a template. If you make it a regular function then the warning reappears:

int get(const std::map <char, std::string>& m) {
    for (const auto& [k, v]: m)
        return v.size();    // warning: loop will run at most once ...
    return 0;
}

Live demo

Arguably, this is a clang bug.

I am also a bit puzzled when you say:

although I don’t really see a value in this warning

I don’t either, so why did you enable it (since, AFAICT, you have to do so explicitly via -Wunreachable-code-loop-increment)?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading