In getopt(3) man page, after arguments are processed in the while loop, there are two lines:

Code:

argc -= optind;
argv += optind;

Could somebody help explain the purpose of these two lines?

I played with the example code in getopt man page, "argc -= optind" seems to set argc to 0.
I also understand that "argv += optind" make the argv pointer pass over current argument string. But just could not figure out why we need to do that.

Adjusting argc & argv is optional. However, the value of optind(which contains the number of arguments which have conformed to the expectations of getopt(3)...) can be used to filter out what has already been processed from those arguments which have yet to be processed.

The following modification to the code found in the getopt(3) manpage illustrates the intended use. Note that all options intended to be processed by getopt(3)must precede those arguments not to be processed by getopt(3):

By adjusting argc & argv after processing the entire argument list, one argument (xyzzy) remains which did not conform to getopt(3)'s intended behaviour. This argument can now be processed later in the code without the programmer needing to take into account all of the getopt(3) processing.

Again, one does not have to change argc or argv. optind merely provides information which can be exploited or ignored.

Quote:

I played with the example code in getopt man page, "argc -= optind" seems to set argc to 0.

This is correct if you only provided command-line options which were completely consumed by getopt(3)'s processing. If the entire list of command-line arguments is processed by getopt(3), then argc & argv will indicate that no other command-line arguments are yet to be processed in some manner. Note that in my example, one more command-line argument is not processed. Adjusting argc & argv might simplify accessing any arguments still to be read, but it is up to the programmer to deal with these command-line arguments as he/she decides is warranted.

Last edited by ocicat; 15th March 2013 at 12:05 AM.
Reason: add clarity

Recognize that the example I provided is limited in the way that optind was used. Here, all command-line parameters understood by getopt(3)had to be provided first. This is not a limitation by getopt(3) itself; it is merely a limitation imposed by how optind was being used to distinguish which parameters were not processed by getopt(3). A more complicated scheme could be implemented which would allow any kind of ordering, but that would be more involved than a twenty line example.