If I have a pointer that points to a string variable array of chars
, is there a difference between typing:
char *name = \"name\";
Yes, there’s a difference. Mainly because you can modify your string but you cannot modify your first version – but the C++ compiler won’t even warn you that this is forbidden if you try.
So always use the second version.
If you need to use a char pointer for whatever reason, make it const
:
char const* str = "name";
Now, if you try to modify the contents of str
, the compiler will forbid this (correctly). You should also push the warning level of your compiler up a notch: then it will warn that your first code (i.e. char* str = "name"
) is legal but deprecated.