Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 13 Feb 2011 15:20:55 +0100
From:      Jilles Tjoelker <jilles@stack.nl>
To:        Matthias Andree <mandree@FreeBSD.org>
Cc:        "Julian H. Stacey" <jhs@berklix.com>, hackers@FreeBSD.org
Subject:   Re: man 3 getopt char * const argv[] - is const wrong ?
Message-ID:  <20110213142055.GA59587@stack.nl>
In-Reply-To: <c367221ee504a36fceb06e813ba6366c.squirrel@webmail.tu-dortmund.de>
References:  <c367221ee504a36fceb06e813ba6366c.squirrel@webmail.tu-dortmund.de>

next in thread | previous in thread | raw e-mail | index | archive | help
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



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