man 3 getopt char * const argv[] - is const wrong ?

Jilles Tjoelker jilles at stack.nl
Sun Feb 13 14:20:57 UTC 2011


On Sun, Feb 13, 2011 at 01:59:38PM +0100, Matthias Andree wrote:
> Am So, 13.02.2011, 13:20 schrieb Julian H. Stacey:
> > Hi Hackers
> > Ref.: man 3 getopt
> > 	int getopt(int argc, char * const argv[], const char *optstring);
> > Ref.: K&R 2nd Ed P.211 last indent, 2nd sentence
> > 	The purpose of const is to announce [objects] that may be
> > 	placed in read-only memory, and perhaps to increas[e] opportunities for
> >     optimization

const only rarely allows optimization, mostly because a declaration like
const foo *p only says that the foo may not be modified via p, not that
it may not be modified at all.

Another important purpose of const is to allow the programmer to
document what is not changed by a function, and have the compiler check
this documentation.

> > optstring is obviously const,
> > but I don't see that argv can calim to be const ?

> The const basically states that the argv[] elements (i. e. the char *
> pointers) are const[ant], or, read another way, that getopt promises not
> to mess with the *pointers* but is free to modify the actual strings
> pointed to (with the usual constraints of not assuming they can be
> extended, for instance) - and I don't see the problem in that.

getopt() should not modify the strings themselves either, but there are
at least two reasons why the type is not const char *const argv[]:

1. Elements of argv are written into char *optarg.

2. Many programs declare main's second argument as char *argv[] which
   cannot be converted to const char *const [], other than via a cast.

-- 
Jilles Tjoelker


More information about the freebsd-hackers mailing list