c++for-loopgcc-warningunused-variablesiota

for-loop counter gives an unused-variable warning


My program has an iterative algorithm with a for-loop that I had written as

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

I really like the fact that it can be written like this, even if the necessary header files are enormous. When I compile it though I get a warning that i is an unused variable.

When I write the for-loop in the old-fashioned way

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

then there is no warning.

I tested this with a minimal program 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; 
} 

and sure enough, compiling it with g++ -Wall --std=c++20 -o for-loop for-loop.cpp gives a warning for the first loop and not the second.

Am I missing something here? I prefer the first notation -- and I know that I can stop the warnings wit -Wno-unused-variables; I would like those warnings, it's just that I am really using the for-loop counter.


Solution

  • i is indeed never used.

    You might add attribute [[maybe_unused]] (C++17) to ignore that warning:

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