Printing command line arguments in C++ I'm learning C++ and here I've written a little toy program that is supposed to list all the arguments passed to it through the command line.

#include &lt;iostream&gt;;
using namespace std;

int main (int argc, char *argv[]) {
  for (int number = 1; number &lt; argc; ++number) {
    cout &lt;&lt; argv[number] &lt;&lt; endl;
  }
  return 0;
}


It is possible to use indexing instead and rewrite it in the following way:

#include &lt;iostream&gt;
using namespace std;

int main (int argc, char *argv[]) {
  int i;

  for (int j = 1; j &lt; argc; ++j) {
    i = 0;
    while (argv[j][i]) {
      cout &lt;&lt; argv[j][i];
      ++i;
    }
    cout &lt;&lt; endl;
  }
   return 0;
}


I personally like the first version more. It doesn't need one more variable and it doesn't need one more cycle, so making use of pointers here seems like a good idea: it helps improve readability and as far as I know performance.

Is this actually a good alternative to the second version that uses indexing? And if so, how could it be improved?
Is this actually a good alternative to the second version that uses indexing? And if so, how could it be improved?


I'm not sure what you're asking here. Obviously the first version is fine; obviously the second version is pretty silly (because it does the same thing as the first version but in a more confusing and verbose way).

As for "using indexing", doesn't the first version also use indexing? What do you think argv[i] is, if not "indexing"? It sure seems like you've got the hang of "indexing" well enough. :)



Your second program is also silly in that it uses a while loop instead of a for loop, even though you have all three pieces of a for-loop (initialization, condition, and increment) in close proximity. Why didn't you use a for loop? Just for practice with different kinds of loops? In that case, I'd dock you points for not using a do-while loop! ;)



To nitpick as long as I'm here:


Everyone will tell you (so you might as well start listening now) that using namespace std is a bad habit. Write std::cout and std::endl explicitly.
You have a stray ; on line 1 — a transcription error, since the compiler wouldn't accept it if you actually tried to compile that.
Your second program uses saner loop index names: i and j. Naming a loop control variable number is more likely to confuse the reader than help them.
Explicit return 0 from main is unnecessary in C++ (and also in C, as of 18 years ago). Omitting it from simple programs like this can help the reader focus on the important stuff instead of the boilerplate.


Putting it all together:

#include &lt;iostream&gt;

int main(int argc, char **argv)
{
    for (int i = 1; i &lt; argc; ++i) {
        std::cout &lt;&lt; argv[i] &lt;&lt; std::endl;
    }
}