0

This should be a pretty straightforward question. I'm brushing up on my C and want to make sure I'm understanding const pointers correctly.

Say I have a function static void penv(const char * const * envp); I think this reads as "penv takes a pointer envp to a const pointer to a const char". Is this correct?

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Jeffrey Rogers
  • 307
  • 1
  • 2
  • 8
  • My advice is to avoid using `const` pointers directly. Instead write typedefs, like `typedef const char* LPCSTR;`. Then it's obvious at first glance what is const and what is not. Clarity of code is usually the most important. – Agent_L Apr 15 '14 at 15:26

3 Answers3

0

Yes, you're right.

The trick is to read the declaration backwards (right-to-left):

static void penv(const char * const * envp);

Here, envp is a pointer (const char * const *) that points to a constant pointer (const char * const), which points to a constant char (const char).

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

The rule says that const should apply to what comes before it, but there's a syntactic sugar:

const char

is equivalent to

char const

thus the reading is:

"penv takes a pointer to a constant pointer to a constant char"

Thus you're correct :)

Marco A.
  • 43,032
  • 26
  • 132
  • 246
0

When you say, "const pointer", it is not clear if you mean that the pointer is constant, or the thing to which it points.

Just read the type backwards (and realize that const char and char const are the same thing.

In this case, envp is a pointer (not constant) to a constant pointer to a constant char.

I.e. envp can be set to point elsewhere, but the pointer(s) to which it points cannot be modified, and neither can the char(s) to which they point.

pat
  • 12,587
  • 1
  • 23
  • 52