🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: net.lang.c++
Article #69

Re: Compiler bug report (#2)

#69
From: Guy Harris
Date: Sun, 23 Mar 1986 22:56
48 lines
2486 bytes
> >>	char *const foo = "hello world";
> >>
> >>	main()
> >>	{
> >>		char *cp = foo;
> >>	}
> >>
> >
> >Surely you would expect that: the erroneous line SHOULD read:
> >>		char *cp = (char *)foo;
> 
> No, why? foo already *is* a (char *) - it just happens to be a constant one.
> ...Seriously tho', why should I have to cast the value of foo from
> "char *const" to "char *" before I can use its value?

You can use its value perfectly well with the following:

/*ARGSUSED*/
int
main(argc, argv)
	int argc;	/* OK, so call me a pedant... */
	char **argv;
{
	const char *cp = foo;
	...		/* one presumes there's more to "main()" than was
			   shown */
}

A "const char *" will do just as well as a "char *" in this case; the only
thing you can't do with the "const char *" that you can do with a "char *"
is modify what it refers to - and if "foo" points to a "const char" array,
you can't modify it anyway (be warned - when ANSI C comes out, or when a C++
compiler that produces assembler or machine code instead of C comes out,
there is an excellent chance that the string in question might be put into a
read-only portion of your process' address space).

In short, why are you trying to evade the type mechanism of C++?  If you
intend to modify what "foo" points to, declare "foo" to be a "char *"
instead of a "const char *"; if you *don't* intend to modify what it points
to, declare "cp" to be a "const char *" instead of a "char *".  Type
checking in general, and "const" type checking in particular, is there for
your own good; use it.  (BTW, why is it 'const char *foo = "string";' and
not 'const char foo[] = "string";'?  People seem to have the tendency to
declare pointers unnecessarily in C and C++.)
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy@sun.arpa	(yes, really)
Technical Details
Message-ID: <3394@sun.uucp>
Path: arc1-ca.pugleaf.net!utzoo!watmath!clyde!burl!ulysses!gamma!epsilon!zeta!sabre!petrus!bellcore!decvax!decwrl!sun!guy
References: <261@euclid.warwick.UUCP> <869@inset.UUCP> <267@euclid.warwick.UUCP>

Show Full Headers
Complete Article Headers
Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Posting-Version: version B 2.10.2 9/18/84 SMI; site sun.uucp
Path: arc1-ca.pugleaf.net!utzoo!watmath!clyde!burl!ulysses!gamma!epsilon!zeta!sabre!petrus!bellcore!decvax!decwrl!sun!guy
From: guy@sun.uucp (Guy Harris)
Newsgroups: net.lang.c++
Subject: Re: Compiler bug report (#2)
Message-ID: <3394@sun.uucp>
Date: Sun, 23-Mar-86 17:56:59 EST
Article-I.D.: sun.3394
Posted: Sun Mar 23 17:56:59 1986
Date-Received: Tue, 25-Mar-86 04:55:45 EST
References: <261@euclid.warwick.UUCP> <869@inset.UUCP> <267@euclid.warwick.UUCP>
Distribution: net
Organization: Sun Microsystems, Inc.
Lines: 48