【问题标题】:for-loop counter gives an unused-variable warningfor-loop 计数器给出未使用的变量警告
【发布时间】:2022-01-07 14:22:57
【问题描述】:

我的程序有一个迭代算法,里面有一个我写的 for 循环

for ( auto i: std::views::iota( 0u, max_iter ) ) { ... }

我真的很喜欢它可以这样写,即使必要的头文件很大。当我编译它时,我收到一个警告,i 是一个未使用的变量。

当我以老式方式编写 for 循环时

for ( unsigned i=0; i < max_iter; i++ ) { ... }

那么就没有警告了。

我用最小程序for-loop.cpp对此进行了测试:

#include<ranges>
#include<numeric>
#include<iostream>

int main() {

    char str[13] = "this is good";

    for (auto i : std::views::iota(0u, 2u)) {
        std::cout << str << "\n";
    }
  
    for (unsigned it=0; it<2; it++ ) {
        std::cout << str << "\n";
    }

    return 0; 
} 

果然,使用g++ -Wall --std=c++20 -o for-loop for-loop.cpp 编译它会为第一个循环而不是第二个循环发出警告。

我在这里遗漏了什么吗?我更喜欢第一种表示法——而且我知道我可以用-Wno-unused-variables 停止警告;我想要那些警告,只是我真的在使用 for-loop 计数器。

【问题讨论】:

  • 在第二个示例中,i 在循环边界检查和循环增量中被视为“已使用”。如果在第一个示例中将 i 重命名为 _,是否还会收到警告?
  • 还可以考虑使用[[maybe_unused]],而不是在全局范围内禁用警告。虽然不是那种情况,但将 i 重命名为 _ 就足够了。
  • @0x5453 - 是的,然后它会给出名称“_”的警告
  • while (std::views::iota( 0u, max_iter ) ) { ... } 是否给您同样的未使用变量警告?
  • for ( auto i: std::views::iota( 0u, max_iter ) ) { ... } 看起来非常复杂,与相应的普通 for 循环相比,更难阅读、理解和维护。程序员的主要目标 (IMO) 应该是好的、干净的、可读的、易于理解的和可维护的代码。但最重要的是它应该简单

标签: c++ for-loop gcc-warning unused-variables iota


【解决方案1】:

i 确实从未使用过。

您可以添加属性[[maybe_unused]] 以忽略该警告:

for ([[maybe_unused]]auto i : std::views::iota(0u, 2u)) {
    std::cout << str << "\n";
}

【讨论】:

    【解决方案2】:

    使用auto i,您永远不会在任何地方使用该变量。

    对于for ( unsigned i=0; i &lt; max_iter; i++ ),您使用i 两次,一次在i &lt; max_iter 中,再次在i++ 中,因此使用了变量

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多