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.
CodePudding user response:
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;
}
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
)?