August 19, 2006
Question: How do you declare a constant/finalized/unmodifiable C-style string in C/C++?
If you answered
then you are dead wrong. Just try adding
and get WTF'd. If you tried it out and got stumped by the result, you're not alone. I thought I was a C/C++ hotshot myself until I read about const-correctness. Digest the following, please:
Working in C/C++ can be such a pain at times. There's just too much mental wrestling involved. You would think that just by saying "const" that it'd be obvious to the compiler that you don't want it to be modifiable. The language doesn't make it easy to express what you want to express. Maybe that's why I'm trying to learn Ruby.
(Many thanks to Miguel who was WTF'd by "const char * const" and challenged me to find an explanation for it.)
If you answered
const char * s = "I AM CONSTANT";then you are dead wrong. Just try adding
s = "DEAD wrong i tell ya";and get WTF'd. If you tried it out and got stumped by the result, you're not alone. I thought I was a C/C++ hotshot myself until I read about const-correctness. Digest the following, please:
// changeable pointer to a constant string
const char * s1 = "i am a constant string";
s1 = "not really"; // legal - literal strings return a char *
s1[2] = '!'; // illegal - s1's contents are read-only
// constant pointer to a changeable string
char * const s2 = "Let's try this again";
s2 = "sure that works"; // illegal - s2 itself is read-only
s2[2] = '!'; // legal - DANGER! will crash program
// constant pointer to a constant string
const char * const s3 = "i am teh ultimate constant string!";
s3 = "yep"; // illegal - s3 itself is read-only
s3[2] = '!'; // illegal - s3's contents are read-onlyWorking in C/C++ can be such a pain at times. There's just too much mental wrestling involved. You would think that just by saying "const" that it'd be obvious to the compiler that you don't want it to be modifiable. The language doesn't make it easy to express what you want to express. Maybe that's why I'm trying to learn Ruby.
(Many thanks to Miguel who was WTF'd by "const char * const" and challenged me to find an explanation for it.)
Labels: C, C++, programming, WTF