Search code examples
ccommand-line-interfacegetoptgetopt-long

why struct option array needs an addtional dummy entry when using getopt_long


For example the option array is:

static struct option const long_options[] =
{
  {"help", no_argument, 0, 'h'},
  {"version", no_argument, 0, 'v'},
  {0, 0, 0, 0}
};

Is it for padding?


Solution

  • Look at the man page for getopt_long():

    int
     getopt_long(int argc, char * const *argv, const char *optstring,
         const struct option *longopts, int *longindex);
    

    The argc and argv pair show one way to say how many entries there are in an array (by explicit count, though since argv[argc] == 0, there is also a sentinel there). The optstring indicates short arguments; the longindex is an output parameter. That leaves only the pointer longopts which means that the function must be able to tell how many entries are in the array without any supporting count (there is no longoptcount argument), so the end of the array is marked by all values zero - a sentinel value.