简体   繁体   English

unreachable-code-loop-increment 警告规则

[英]unreachable-code-loop-increment warning rules

Consider the following code (clang).考虑以下代码 (clang)。 It has two identical loops explicitly terminated on the first iteration.它有两个相同的循环,在第一次迭代时明确终止。 One of them throws a warning (an error if -Wpedantic -Werror).其中之一会引发警告(如果是 -Wpedantic -Werror,则会引发错误)。 The other does not.另一个没有。 Trying to understand why.试图理解为什么。 The code can be tested on Godbolt here代码可以在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.使用循环迭代器。

The difference in behaviour seems to be a side-effect of making get a template.行为上的差异似乎是 making get a template 的副作用。 If you make it a regular function then the warning reappears:如果您将其设为常规 function,则会再次出现警告:

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.可以说,这是一个 clang 错误。

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 )?我也不知道,那你为什么要启用它(因为 AFAICT,你必须通过-Wunreachable-code-loop-increment明确地这样做)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM