Posted by: arch119 August 4, 2005
Information technology
Login in to Rate this Post:     0       ?        

>>testdirector, gidilat I should admit that the use of "const" keyword is pretty confusing. There are 2 main contexts it is used in : 1) as in [[ const int i = 5; ]] Well, in this case as expected the value of i cannot be modified later on. 2) as in [[ const char *p="abcde"; ]] Now we had various opinions on that. Let's consider the following example : const char *p="abcde"; // was explained by gidilat. char q[] = "fghik"; // a character sequence enclosed within double quotes is not necessarily a string literal. Here, it is used to initialize an array and is modifiable later on. q[4]='j'; // works fine p=q; /*works fine. That's what is confusing me. Gidilat, in his discourse, mentioned that "const char *p tells p that p is a pointer to const char. You can only use p to point to const chars." But, here p is pointing to a region which is modifiable and it works fine!! */ p[2]='a'; //as expected this will produce error (compile error). So, IMO, const char *p just says that the memory region pointed to by p, shouldn't be modified. [ Neither does it tell the compiler explicitly to store the string pointed by p into a read-only region nor does it ensure that p can only point to const chars] (And if anybody tries to change a memory region using p, it can be detected at the compile time).
Read Full Discussion Thread for this article