Why we use argc as argument in getopt() function? Why we use argc as argument in getopt() function? unix unix

Why we use argc as argument in getopt() function?


In my observation argc is there to write simple code and the argv NULL to write defensive code.

argv and argc has been in main's signature since the very beginning of C, so has the NULL at the end of the argv list. I've looked at many C programs since then and almost none of them depend on that NULL. Rather they depend on argc to control the array depth as it is simpler and more reliable. However, the defensive programmer will also look for that NULL as well as using argc and getopt() should use argc to complain if it's called too many times.

Also, I've seen code that plays games to reuse getopt() to parse secondary "command lines" for commands given to the application. Not all of those put a NULL on the end of the list (mine did, though).


The C standard does guarantee that argv[argc] is a NULL pointer:

C Standard, §5.1.2.2.1.2:

If they are declared, the parameters to the main function shall obey the following constraints:

...

— argv[argc] shall be a null pointer.

Technically, all you (and the function getopt) really need is argv - something like this will process all arguments:

int i;for(i = 0; argv[i]; i++){    puts(argv[i]);}

However, there is nothing stopping you (or the author of getopt) from using argc as a loop guard instead. This is equally valid:

int i;for(i = 0; i < argc; i++){    puts(argv[i]);}

So, if the function says it requires argc to be passed, then pass argc to it, because it probably uses it to form that type of loop.