the "const" qualifier

Andy Fyfe andy at cit-vax.Caltech.Edu
Fri Oct 27 20:32:05 AEST 1989


When I look at a prototype of the form
	extern char *strcpy(char *to, const char *from);
I'd like to think of it as not only telling me what the parameter
types are, but also telling me that strcpy will not change the
characters pointed at through "from".  

I had previously brought up the example of "execv", and Doug
Gwyn suggested:
>Personally I would opt for
>	extern int execv( const char *path, char *const *args );
>as the most restrictive declaration that doesn't cause user hassles.

I would rather see the fully constrained
	extern int execv( const char *path, const char *const *args );
With just 
	extern int execv( const char *path, char *const *args );
I would wonder about the "safety" of passing a "const char **" as the
second argument.  Explicitly casting the "const char **" to a "char **"
would work, but only with something external (or a comment or
something) to tell me it's "safe".  Yet to use the fully constrained
version causes compiler warnings in the typical case of passing a "char
**", unless a cast is present.  Such a cast strikes me as a bit
incongruous, as what's allowed with the pointer after the cast was
allowed to begin with.

I can be somewhat pedantic.  I assume that if a compiler puts a literal
string constant in read-only memory (as Gnu CC does, for example), it
should give that string the type "const char *" when type checking (and
Gnu CC will do this, with a -W... option).  Getting something that I
think really should have the type "const char **" is easy (any array of
pointers to literal strings), and since a write into such a string when
using a compiler like Gnu CC can cause a run-time memory fault, I'd
just as soon have the compiler doing some extra checking for me (I'm a
bit too error-prone to do it myself).

Thanks to those who've responded.

Andy Fyfe
	    andy at csvax.caltech.edu wjafyfe at caltech.bitnet
	    andy at cit-vax.UUCP   (...!ames!elroy!cit-vax!andy)



More information about the Comp.std.c mailing list