How to perform a range-based c++11 for loop on char* argv[]?


I would like to try out c++11 range-based for loop on char* argv[] but I am getting errors. By current approach is :

for( char* c : argv )
   printf("param: %s \n", c);                                                                    

and in my makefile I have the following line :

g++ -c -g -std=c++11 -O2


argv is an array of pointers to raw strings, you can’t obtain a range from it directly.

With C++17 you can use std::string_view to avoid allocating strings:

for (auto && str : std::vector<std::string_view> { argv, argv + argc })
    std::printf("%s\n",; // Be careful!
    std::cout << str << std::endl;   // Always fine
    fmt::print("{}\n", str);         // <3

Take caution when using string_view with printf because:

Unlike std::basic_string::data() and string literals, data() may return a pointer to a buffer that is not null-terminated.

argv always contains null-terminated strings so you’re fine here though.

Without C++17 you can simply use std::string:

for (auto && str : std::vector<std::string> { argv, argv + argc })
    std::printf("param: %s\n", str.c_str());

Starting from C++20 you can use std::span:

for (auto && str : std::span(argv, argc))
    std::printf("param: %s\n", str);

Answered By – Chnossos

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.