|
From: Ioannis V. <no...@ho...> - 2002-06-15 03:06:54
|
> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of Abhijit Shylanath
> Sent: Friday, June 14, 2002 8:13 PM
> To: Dev-C++ Mailing List
> Subject: [Dev-C++] const modifier?
>
>
> I was just going through the sources of the class libraries
> in Turbo C++
> version 3.0, and found this code. How does the program modify
> aPtr even
> though it says it's a const?
const char *p means that it can not change the contents of the object
where it points. Example:
const char *p="constast string 1";
p="constant string 2";
To not be able to point to somewhere else:
// constant pointer
char * const p=some_char_array;
const char *const p="something";
p cannot point to somewhere else and cannot changge the object where it
points. For example:
cout<<p[2]; // valid
p[2]='7'; // invalid
p="something else"; //invalid
for(int i=0; i<18; i++)
cout<<"did you know that?"[i]; // valid
>
> -------CLASSLIB/SOURCE/STRNG.CPP------
> String::String( const char *aPtr )
> {
> if ( aPtr == 0 )
> aPtr = "";
>
> len = strlen( aPtr ) + 1;
> theString = new char[ len ];
> CHECK( theString != 0 );
> strcpy( theString, aPtr );
> }
> --------------------------------------
>
> After seeing this, I tried compiling the following file in
> MingW, and it did
> (with -Wall, no warnings)
>
> --------------------------------------
> void do_stuff(const char *buf)
> {
> if(!buf)
> buf = "";
> }
>
> int main()
> {
> do_stuff(0);
> return 0;
> }
> --------------------------------------
>
> How? Doesn't
> buf = "";
> translate to assign "" to buf?
A literal behaves like an array of chars. An array behaves like a
pointer to its first element. The first element here is '\0' (which is
always 0). I did not understand the last question btw.
Since you learn C++ i recommend you leave the low level stuff for
later, and learn to deal C++ as a high level language, and not as C.
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.cjb.net
* Alternative URL: http://run.to/noicys
|