Richard<rg****@gmail.comwrites:
<snip>
I wonder if its as simple as "the const element is the one to the right
of the const keyword"?
const char *p : the char is const
char * const q : q is const
Not if people use odd orders like char const *p;
There is a simple rule the everyone sing C should know. It is one of
those simple rules that is hard to write down in exact detail (I have
done in some old posts) but the gist of it is:
(1) Find the identifier (i.e. the thing being declared/defined).
(2) Read the declaration outwards from the name, always going to
right if you can and then going left when you can't. Imagine
crossing off the symbol as you voice them so you never voice a
symbol or keyword ore than once.
(3) Bracket nesting has to be respected. I.e. when you hit a ")"
going right, you must read anything left inside these brackets
(by reading to the right now) before you cross them off as done.
So for the odd:
char const *p
^ "p is a" (now we can't go right)
^ "pointer to (a)"
^ "constant"
^ "char"
char *const p
^ "p is a"
^ "constant"
^ "pointer to (a)"
^ "char"
You can say "read-only" for "const" if you prefer to get slightly
closer the real meaning.
Let's try a more complicated one:
int *const *p[6]
^ "p is an" (here we can go right so we do)
^ "array of 6"
^ "pointers to"
^ "constant"
^ "pointers to"
^ "int"
int (*f)(int)
^ "f is a" (we can't go right until the () are done)
^ "pointer to a" (the () are not done so we go right)
^ "function taking"
^ "an int"
^ "and returning"
^ "int"
I would be a liar if I didn't say I always highlight such and call up
cdecl in my editor to be sure to be sure.
No need if use this rule. You need to do it a few times (with cdecl at
hand) to work out the wrinkles of how you like to say each symbol but
then you can read any C type with ease.
The trickiest part is when you are reading what the syntax calls a
type name -- the bit in the brackets of a cast and in some sizeof
expressions. Here, the name will be missing so you have to work out
where the name would be. I don't find that hard, but it helps to try
a few to get the hand of it.
[This lead to another hand rule: a C type name is a declaration with
the name missing.]
--
Ben.