Is `char const *foo;' legal?

Spencer Garrett srg at quick.COM
Thu Jan 11 21:40:08 AEST 1990


In article <25ABBF93.9618 at paris.ics.uci.edu>,
 rfg at paris.ics.uci.edu (Ron Guilmette) writes:
> I have recently learned that the GNU C compiler accepts the following
> declaration without complaint:
> 
> 	char const *foo;
> ...
> So let me just ask the general question: "Are such declarations both
> syntactically and semantically legal?"
> ...
> One other question.  If this form of declaration *is* legal, then
> does the standard contain any verbage which would clarify the type of
> `bar' in the following example?
> 
> 	void foo (char const bar[])
> 	{
> 	}
> 
> GCC accepts this declaration, and it binds the `const' with lower `priority'
> that the `[]'.  Thus, the type of `bar' is taken as pointer to constant char.

Not only legal, but IMHO preferred.  Think of "const" and "volatile"
not as type names, but as *operators* (on a par with *) with the
unusual characteristic of being allowed to float all the way to the
left of the type names and storage-class indicators (which sometimes
makes the declaration read better (in English)).  Parentheses aside,
they modify the declaration to their right, just like *.  I prefer to
write:

char		const *foo;

to emphasize that "const *foo" is a char.  When you take the * off to
look at the named variable itself you have taken off the const keyword
as well, so you know that the pointer isn't constant, just the chars.
In the same way, you read

char	       *bar[];

as an array of pointers, so

char		const bar[];

would be an array of const chars.  Use in a parameter declaration
implicitly turns "array of" into "pointer to" in either case.
I hope this helps.



More information about the Comp.std.c mailing list