The RubeTube

Life's a cube.  Solve it.


August 19, 2006
Question: How do you declare a constant/finalized/unmodifiable C-style string in C/C++?

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-only


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.)

Labels: , , ,


About me



Mark Punzalan
a.k.a. "Punzki"
Location: Redmond, WA
Occupation: Softie

Current tag-line:
I'm alive!
Now reading:
The Bible (really!)
Latest obsession:
NBA playoffs (via streaming)

Around the web:
punzki @ punzki.com
punzki @ Blogger
punzki @ del.icio.us
punzki @ LinkedIn
punzki @ Friendster
punzki @ Bloglines
punzki @ YouTube
punzki @ Multiply

Email me: punzki@gmail.com

Search

RSS feed



What is RSS?

AdSense


Et cetera




Locations of visitors to this page


Pinoy Top Blogs
Fantasy Sports Live!
Firefox 2

Creative Commons License
This work is licensed under a Creative Commons License.

Powered by Blogger
and Blogger Templates