Subject: Re: Sample code in getopt(3)
To: None <>
From: der Mouse <mouse@Rodents.Montreal.QC.CA>
List: tech-userlevel
Date: 06/24/2003 22:59:59
[compressed vertically -dM]
>>> while ((c = getopt(argc, argv, "0123456789")) != -1) {
>>>         switch (c) { case '0' ... '9':
>>>                 p = argv[optind - 1];
>>>                 if (p[0] == '-' && p[1] == ch && !p[2])
>>>                         length = atoi(++p);
>>>                 else
>>>                         length = atoi(argv[optind] + 1);
>>>                 break;

>> My first reaction is that it's intended to handle multi-digit
>> arguments [...]

> it's supposed to differentiate between -3 and -37 as options.  -3
> will match the former case (and optind will have been incremented).
> -37 will match the latter case (since option flag eating will not be
> done yet).

All the following assumes s/ch/c/ in the if, of course.

Actually, -37 will match the latter case the first time around, when
'3' is returned; the second time around, when '7' is returned, it will
set length to the number in the following argument (skipping the first
character), or drop core if there is no following argument.  Note the
lack of any variable frobbing to tell getopt to skip the rest of the
argument after the processing when '3' is returned.  If the -37 happens
to follow an argument -3 (for any reason), length will be set to 3 when
the '3' is returned for the first digit of the -37.  Besides breaking
in various ways, this depends heavily on setting "length" being
idempotent; I think it should be removed from the manpage - it's too
broken to be acceptable as a usage example (IMO of course).

Unless getopt special-cases digits internally.  This is not documented
in getopt(3); while a little thought applied to the manpage allows one
to deduce that dash, colon, and question mark are not usable normally
as option characters, there's no indication that any other characters
are in any way special (and for even those three there's no explicit
mention of the restriction, just implications of other statements).
The page even explicitly uses "character" rather than "letter" when
speaking of the third argument to getopt.

Basically, this just reinforces my long-standing feeling "getopt(3) is
a severely botched design; don't use it".

/~\ The ASCII				der Mouse
\ / Ribbon Campaign
 X  Against HTML
/ \ Email!	     7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B