The Pointer The Pointer - 1 year ago 81
C Question

The variable optarg of getopt()

I've read through the documentation for

, but I do not find the explanations of

I cannot find any other sources which explicitly and clearly explain general information about

I would appreciate it if someone could clarify and elaborate on the general information about

I would like to know:

  • What

  • How
    gets its value.

  • The documentation mentions something about colons changing the value of

The documentation has examples of how to use
. I am more-so interested in clear and elaborate explanations of the variable itself.

Answer Source

The man page says, (emphasis mine)

optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in optarg, otherwise optarg is set to zero. [...]

and the given code snippet below shows the usage.

while ((opt = getopt(argc, argv, "nt:")) != -1) {
    switch (opt) {
    case 'n':
        flags = 1;
    case 't':
        nsecs = atoi(optarg);
        tfnd = 1;
    default: /* '?' */
        fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",

To elaborate, by seeing the syntax "nt:" we can understand that the option n does not need any argument but option t will have a following argument to it. So, when the option t is found, the corresponding argument is stored into optarg and can be retrieved by accessing optarg.

So, basically, getopt() will return the option and optarg will return the supplied argument for that option, if any.

In case the binary is run like ./a.out -t 30, then when getopt() returns t, optarg will be holding a pointer to a string containing 30 (not an int, mind it).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download