Archived

This topic is now archived and is closed to further replies.

WiseElben

const Keyword

Recommended Posts

char a_string[64] = "Hello";
 
const char* buff1 = a_string;
char* const buff2 = a_string;
 
buff1 = "Hi there"; // It's totally legal to set buff1 to another pointer to constant data

*buff2 = 'w'; // It's totally legal to change any value pointed to by buff2

At GT's const Keyword tutorial, it states that it is legal. I don't understand why it is legal.
Visit my game programming website at www.wiseelben.com [edited by - WiseElben on July 27, 2003 10:37:29 PM] [edited by - WiseElben on July 27, 2003 10:37:51 PM] [edited by - WiseElben on July 27, 2003 10:45:45 PM] [edited by - WiseElben on July 27, 2003 10:52:47 PM] [edited by - WiseElben on July 27, 2003 10:53:04 PM]

Share this post


Link to post
Share on other sites
oh, it''s simple. For buff1 it''s legal because the pointer itself is not constant. So that means we can have the pointer point to something else, which is what the code''s doing for buff1.

For buff2, the pointer is constant but the value pointed to is not constant. We won''t be able to redirect buff2 to point to something else but we can change the value buff2 is pointing to.

Does that make any sense?





--{You fight like a dairy farmer!}

Share this post


Link to post
Share on other sites
The placement of const in the declaration determines what''s constant and what is variable. For buff1 the constness applies to the characters pointed at (in which case it''s OK to change the pointer) and for buff2 it applies to the pointer itself (which means it''s OK to change the things being pointed at but not the pointer).

Both could be made const with a declaration such as

const char* const buff3 = a_string;

and neither assignment would be legal for buff3.

Share this post


Link to post
Share on other sites
quote:
Original post by spock
The placement of const in the declaration determines what''s constant and what is variable. For buff1 the constness applies to the characters pointed at (in which case it''s OK to change the pointer).


So that means the constantness is the a_string?

buff1 = "Hi there";

So what does that change? The memory of buff1 to somewhere called "Hi there"?




Visit my game programming website at www.wiseelben.com

Share this post


Link to post
Share on other sites
quote:
Original post by WiseElben
So that means the constantness is the a_string?

buff1 = "Hi there";

So what does that change? The memory of buff1 to somewhere called "Hi there"?



That changes the pointer buff1 so that it points to wherever the memory for the string literal "Hi there" is.

Share this post


Link to post
Share on other sites