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

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

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

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]] to ignore that warning:

for ([[maybe_unused]]auto i : std::views::iota(0u, 2u)) {
    std::cout << str << "\n";
}
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