Hi All,
I have seen lots of people asking difference between const pointer and a pointer pointing to a const object.
C++ is lots funny and it so happened that I recently had to come across these feature in my work . for a moment even I was confused , but only when I went to the basic principles ,thing s got set right.
Ok ,so here is a snippet which should clear your doubt.
#include
int main(){
char const *p1 = "A";
char *const p2= "B";
const char const *p3="C";
//consider the below operation ;
*p2 =”C” ; //Allowed
p2 = “D” ; //Not Allowed
*p1= “C” //Not Allowed
p1= “D” //Allowed
*p3=”C”; //Not allowed
p3=”D” ; //Not allowed
return 0;
}
PS: const char * and char const * are same because C++ standard suggest that you can put const keyboard in front of a
type or variable.
Though funny that’s how it works 🙂
For more info see below links
Nice one, at times though I feel what am I losing if I am only towards Java which does not have any concept on pointers. Do we lack something without having pointers.
Aniket, Basically you would miss the fun involved in accessing and modifying data at register level if you want to 🙂 As said ” with great power comes great responsibilities” , I Think by using pointers we must be cautious enough to use it wisely
yeah…agree with you on that, but still as to why pointers were never included in Java or .C#, . I mean reduction of complexity and to security to certain extent can be possible arguments. So was it that the disadvantages weighed more than the advantages. And regarding changing values at the register level, I guess when we come to level of byte manipulation then the question of a programming language turns turtle , because at that point you can modify anything.
const char const *p3=”C”; i think you meant const char *const p3;
And I would recommend using some address rather than “A” since you don;t want unexpected behavior 🙂
Yes Shashank, You are right. But I just wanted to keep it simple .