From owner-freebsd-hackers@FreeBSD.ORG Sun Feb 13 14:20:57 2011 Return-Path: Delivered-To: hackers@FreeBSD.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 7CC8D106566B; Sun, 13 Feb 2011 14:20:57 +0000 (UTC) (envelope-from jilles@stack.nl) Received: from mx1.stack.nl (relay04.stack.nl [IPv6:2001:610:1108:5010::107]) by mx1.freebsd.org (Postfix) with ESMTP id 1905D8FC15; Sun, 13 Feb 2011 14:20:57 +0000 (UTC) Received: from turtle.stack.nl (turtle.stack.nl [IPv6:2001:610:1108:5010::132]) by mx1.stack.nl (Postfix) with ESMTP id 1CC171DD633; Sun, 13 Feb 2011 15:20:56 +0100 (CET) Received: by turtle.stack.nl (Postfix, from userid 1677) id 03CAA17316; Sun, 13 Feb 2011 15:20:55 +0100 (CET) Date: Sun, 13 Feb 2011 15:20:55 +0100 From: Jilles Tjoelker To: Matthias Andree Message-ID: <20110213142055.GA59587@stack.nl> References: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.21 (2010-09-15) Cc: "Julian H. Stacey" , hackers@FreeBSD.org Subject: Re: man 3 getopt char * const argv[] - is const wrong ? X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sun, 13 Feb 2011 14:20:57 -0000 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