Search code examples
cunixgetopt

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


I have recently started learning C language so I don't much about the functions of C.

Recently I saw a program written in C on Internet article. It was like this:-

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int i = 0;
    int j = 0;
    char ch;

    ch = getopt(argc, argv, "n:");
    if(ch == 'n')
    {
        j = atoi(optarg);
    }

    while(j--)
    {
        printf("%i\n",j);
    }
    return 0;
}

Can anyone tell what is the actual purpose of argc in getopt() function? Does it uses argc as for upto where it should read options?


Solution

  • 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.