argv is an array of constant pointers to characters
char * const argv[] // 1
argv is an array of pointers to characters, which are constant
const char * argv[] // 2
Is there a tip to remember number 1?
argv is an array of constant pointers to characters
char * const argv[] // 1
argv is an array of pointers to characters, which are constant
const char * argv[] // 2
Is there a tip to remember number 1?
const char * argv[] // 2
can also be written:
char const * argv[] // 3
because C doesn't care about the order of const in the type. If you write it this way, then the thing actually const
is the thing to the left of the keyword const
. The form where const
is first is the one exception to that rule; but in that case there's nothing to the left of const
so it is easy to avoid that case with this rule of thumb.
char* // mutable pointer to mutable char
char const* // mutable pointer to constant char
char * const // constant pointer to mutable char
char const* const // constant pointer to constant char
char * const argv[]
There are simple rules, as cskoala mentioned in his answer:
Find identifier
char * const argv []
|
identifier
1
Read all element to the right of identifier, left-to-right
char * const argv []
| |
identifier array
1 2
Read all element to the left of identifier, right-to-left
char * const argv []
| | | | |
char pointer const identifier array
5 4 3 1 2
Result: (1) argv
is (2) an array of (3) constants of type (4) pointer to (5) char
Other examples.
char const * argv []
| | | | |
char const pointer identifier array
5 4 3 1 2
Result: (1) argv
is (2) an array of (3) pointers to (4) constants of type (5) char
char const * const argv []
| | | | | |
char const pointer const identifier array
6 5 4 3 1 2
Result: (1) argv
is (2) an array of (3) constants of type (4) pointer to (5) constant of type (6) char
There is notably ugly exception to this simple rule. For some reason C allows to place const modifier to the left of type, like in your example:
const char * argv []
| | | | |
const char pointer identifier array
4 5 3 1 2
In my opinion it's better to avoid such declarations, for consistency. It's often leads to confusion or errors.
At my university, we're taught something called the "Right-Left Rule" which is pretty much a way to read variables in a way that tells you what they are.
Here's the link to the page: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html
It looks like a lot but after a few examples, it helps makes sense of a lot of these type of things! =]