in the code

const char* buf

what is the constant? The pointer or buf?

Recommended Answers

All 5 Replies

The character(s) pointed to by buf are treated as read-only. To make the pointer itself const, place the keyword after the asterisk:

char * const buf;       // const pointer to non-const char
const char *buf;        // Non-const pointer to const char
const char * const buf; // const pointer to const char

Thank you.
But now I'm confused about the placement of the asterisk.
Does const char* buf mean the same thing as const char *buf or
const char * buf?

For the most part, whitespace in C is ignored. All three of your examples are functionally identical. You could also say const char*buf and it'll work fine because the tokens aren't ambiguous. However, constchar won't work.

Another bit of trivia is that const doesn't have to go before the type: char const *buf. This can make declarations easier to decipher as they're typically read inside out and right to left: char const * const buf reads as "buf is a const pointer to const char".

Thank you again. A lot of code has just gotten a lot less confusing.

Good luck Kent! :-) Sometimes this stuff gets my eyeballs rolling, and I've been doing it for 30+ years! Deceptikon's answer was to the point. Couldn't state it better myself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.