Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 11 Sep 2006 17:57:26 +0530
From:      "Amarendra Godbole" <amarendra.godbole@gmail.com>
To:        freebsd-questions@freebsd.org
Subject:   Sequence of execution of getopt() and usage()...
Message-ID:  <294439d20609110527m2093cde8r4a93e391826f2b17@mail.gmail.com>

next in thread | raw e-mail | index | archive | help
Hi,

This is a general FreeBSD source related question, and I am posting it
here, as it did not fit in any other FreeBSD lists...

While browsing through sources for different userland utilities (cat,
chmod, and so on), I noticed that in main(), first getopt() is called
in a while loop, and then the check for the number of arguments passed
is done. Something like this (from chmod.c):

int
main(int argc, char *argv[])
{
...
        while ((ch = getopt(argc, argv, "HLPRXfghorstuvwx")) != -1)
...
        if (argc < 2)
                usage();
...
}

Can't we check for the number of arguments *before* calling getopt()?
Something like:

int
main(int argc, char *argv[])
{
...
        if (argc < 2)
                usage();
...
        while ((ch = getopt(argc, argv, "HLPRXfghorstuvwx")) != -1)
...
}


This might make it a bit more efficient, though I don't have numbers'
to prove this.

I observe a similar pattern in other utilities too - which might mean
that there was a sound reason as to why it was done this way. Can
someone be kind enough to explain this? Thanks in advance!

Best,
Amarendra



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?294439d20609110527m2093cde8r4a93e391826f2b17>