const char* question..

I've used c strings for years. I hardly ever use const char* at all. So I don't know all of its ins and outs. I ran across this in some code today.

const char* aStr;

const char* anotherStr;

anotherStr = aStr;

Now, I thought const meant that, whatever it was after, could not change. How can you assign something to a const?

-jim lee

The pointer is not constant but the object it is pointing to, a string in this case, is a constant.

Read this for a good understanding of the const keyword:

http://duramecho.com/ComputerInformation/WhyHowCppConst.html

guix:
Read this for a good understanding of the const keyword:

The C++ 'const' Declaration: Why & How

I found this in the quoted link in the context of class methods:

const int*const Method3(const int*const&)const;

The author admits that it "can get confusing".

jimLee:
I've used c strings for years. I hardly ever use const char* at all. So I don't know all of its ins and outs. I ran across this in some code today.

const char* aStr;

const char* anotherStr;

anotherStr = aStr;




Now, I thought const meant that, whatever it was after, could not change. How can you assign something to a const?

-jim lee

The const binds to the char, not char*. If you want a constant pointer you say

const char * const aStr = "...";

@econjack will be along shortly... :smiley:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.