C getopt multiple value

I know this is quite old but I came across this in my search for a solution.

while((command = getopt(argc, argv, "a:")) != -1){

    switch(command){
        case 'a':

        (...)

        optind--;
        for( ;optind < argc && *argv[optind] != '-'; optind++){
              DoSomething( argv[optind] );         
        }

        break;
    }

I found that int optind (extern used by getopt() ) points to next position after the ‘current argv‘ selected by getopt();
That’s why I decrease it at the beginning.

First of all for loop checks if the value of current argument is within boundaries of argv (argc is the length of array so last position in array argv is argc-1).
Second part of && compares if the next argument’s first char is ‘-‘. If the first char is ‘-‘ then we run out of next values for current argument else argv[optind] is our next value. And so on until the argv is over or argument runs out of values.

At the end increment optind to check for the next argv.

Note that because we are checking ‘optind < argc‘ first second part of condition will not be executed unless first part is true so no worries of reading outside of array boundaries.

PS I am a quite new C programmer if someone has an improvements or critique please share it.

Leave a Comment