Command Line – Checking Minimum Number of Command-Line Arguments While Allowing Help Switch

command lineorder

I just ran into an odd scenario. I’m sure that I must have run into the same situation in the past and yet somehow not noticed it until now.

I am writing a program that requires at least two command-line arguments. Dealing with this is simple enough, just check that there are sufficient arguments. For example:

A:  if (argc < 3) PrintHelpAndQuit();

However, I also want to allow the user to specifically request the help-screen(s) using a single command-line argument. For example:

B:  if (args[1] == "/?")  PrintHelpAndQuit();
C:  if (args[1] == "/?1") PrintHelp1AndQuit();
D:  if (args[1] == "/?2") PrintHelp2AndQuit();

The problem is that if I put line A first, it ensures that at least two arguments were specified, which prevents then lines B, C, and D from being called, and so the user cannot access those screens.

If I put line A after the others, then the program will crash if no arguments are specified (accessing the first member of the argument array is undefined).

There seems to be (only?) two ways to approach this:

  • Put the help-screen lines in a conditional block that checks that there is at least one argument (which duplicates the work of line A):

    if (argc > 1) {
      if (args[1] == "/?...
    }
    
    if (argc < 3) PrintHelpAndQuit();
    

  • Put an extra line at the top that checks if there are no arguments and prints help and quits if so:

    if (argc < 2) PrintHelpAndQuit(); // now almost entirely duplicates line A
    if (args[1] == "/?...
    if (argc < 3) PrintHelpAndQuit();
    

Both of these approaches are redundant to varying degrees.

How do others deal with this situation? Is there a more elegant (and less redundant) way to require a minimum number of arguments without precluding a single argument?

Best Answer

Logically, the problem as defined requires a check that there is at least one argument for the help case, as well as a check that there are at least two arguments for the normal use case.

Think about what you have to say to describe the program's behavior:

[The program] requires at least two command-line arguments...

Then

I also want to allow the user to specifically request the help-screen(s) using a single command-line argument.

Even to describe the behavior in words, you need two different requirements about the number of arguments. It is no surprise that the code similarly needs two requirements. Having two checks is not redundant, because it is the minimum amount needed to logically test for the valid options.

Related Topic