I really didn't think that would work, but it did.
The following works just fine and does what I intended.
(Tested w/ g++ version 3.4.6, not the latest)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// constgrief.cpp
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
const char* WhereWeAre = "We are here";
cout << WhereWeAre << endl;
WhereWeAre = "Now we are there";
cout << WhereWeAre << endl;
WhereWeAre = "Now we are neither here nor there";
cout << WhereWeAre << endl;
WhereWeAre = "All Done";
cout << WhereWeAre << endl;
return 0;
}
|
I thought that having defined WhereWeAre as
const char* I would be able to assign it once, and then never again. I was wrong.
The secret is in how const is used. As written above, WhereWeAre is "a pointer to a constant character".
In order to create the problem I thought I was going to have WhereWeAre needs to be defined this way:
|
const char* const WhereWeAre = "We are here";
|
or
|
char* const WhereWeAre = "We are here";
|
Which will give the following compile errors:
constgrief.cpp: In function `int main(int, char**)':
constgrief.cpp:13: error: assignment of read-only variable `WhereWeAre'
constgrief.cpp:17: error: assignment of read-only variable `WhereWeAre'
constgrief.cpp:21: error: assignment of read-only variable `WhereWeAre'
The trick is in clearly understanding how const syntax works. When const is directly in front of the variable name then the variable itself becomes constant.
I was stuck in a paradigm and didn't see the solution right in front of me.
Thanks for digging me out!