Using getopt to parse multi-argument options

John Woods john at frog.UUCP
Tue Jan 24 15:21:00 AEST 1989


In article <3146 at ttrdc.UUCP>, levy at ttrdc.UUCP (Daniel R. Levy) writes:
N>In article <1989Jan19.192946.15825 at utzoo.uucp>, henry at utzoo.uucp (Henry Spencer) writes:
e>< This is not portable; it assumes a specific implementation of getopt.
c>< Unless things have changed, the getopt(3) documentation makes no promise
r>< that user changes to optind will be reflected back into getopt's innards.
o>Literally taken, you are quite right.  I am reading between the lines of
m>the man page and making an educated guess.  Can you suggest a reason for
a>the statement "Because optind is external, it is normally initialized to
n>zero automatically before the first call to getopt," other than the
c>implication that optind's value will influence the behavior of getopt?
y>I mean, why else should we care what optind is prior to at least one usage
 >of getopt?

Interesting.  The SVID (Issue 2, Volume 1) says "The external variable optind
is initialized to 1 before the first call to the function getopt."  No
statement of cause-and-effect, and a different initializer from your manual
page.  This also does not imply that optind influences getopt(), it merely
implies that optind always has a reasonable value.

If you really have to have a program which doesn't use getopt() argument
semantics, why bang on getopt() to fool it into doing what you want?  At the
very worst, writing your own getopt() with your own semantic variations can't
be all that hard (I wrote one a long time ago in a small amount of time, and
I bet Henry's version didn't take all that long, either).  That way, you can
make sure that the next version of your libraries don't surprise you, and you
have real documentation for what your preferred argument semantics are ("Use
the Source, Luke!").  The real motivation for putting getopt() in the library
isn't saving people gobs of coding time, it was to make having a uniform
command syntax temptingly inviting.
-- 
John Woods, Charles River Data Systems, Framingham MA, (508) 626-1101
...!decvax!frog!john, john at frog.UUCP, ...!mit-eddie!jfw, jfw at eddie.mit.edu

Presumably this means that it is vital to get the wrong answers quickly.
		Kernighan and Plauger, The Elements of Programming Style



More information about the Comp.lang.c mailing list