Thursday, January 14, 2010

const char* versus const char* const

From the "WTF/programming" department.

This is one I've learned and forgotten more than once. Maybe writing it down will make it stick. We'll see.

In the C programming language const-ness of pointers can refer to the pointer itself as well as the object being referenced.

const char* foo = "Foo!";

Here foo is a mutable pointer to an immutable C string.

char* const bar = "Bar!";

Now with bar we have an immutable pointer bar to a mutable C string.

const char* const baaz = "Baaz!";

Boom. Now we have baaz: an immutable pointer to an immutable C string.

So what's up with the bizarre syntax? I mean, the trailing const style is almost never seen in actual C code. It's not just me that finds this obtuse.

My poor dyslexic head can't keep this sort of nonsense straight. I mean it all makes sense now, but next week I'll only remember "const char* const" means something useful. And of course all this is compile-time only and can be fairly easily circumvented with casting.

WTF. Take away is (as it often is): don't get too clever.

No comments:

Post a Comment