Is is necessary to have the 'const' in declaring char const *ptr = "some characters"?
Since they both po开发者_JS百科int to characters which can not be modified. What is the benefit of having the const in the first one? Is it just to tell the compiler to watch out for any code that may do something like ptr[1] = 'a'
char const *ptr = "some characters"
char *ptr = "some characters"
Yes, so that when you try to modify the contents through the pointer you will get a compiler error instead of nasty surprises at the run time.
In C++, the conversion of const char[N]
, which is the actual type of a string literal, to char *
, is deprecated and no longer works in C++11 (C++11, C++03 §4.2). So, #2 is newly broken. A C++98/C++03 compiler usually produces a warning; a C++0x/C++11 compiler should refuse entirely.
The main point of const
is that the compiler can tell you when an attempt is made to remove or violate it. Even if you don't plan to try to modify those characters, the advantage is that an error occurs if you accidentally do.
You can always work around it with const_cast
, although in this case where the memory is likely to be read-only, physically or via the MMU, there cannot be anything to work around.
The use of const
is very rarely "necessary", from a pure "executing this code will have the desired results" point of view.
Copious use of const
is an immense help to anyone reading the code an trying to understand it, however. This is worth a lot. I recommend always putting const
everywhere it will work.
In a similar vein, always declare functions that are intended to be strictly local as static
, for pretty much the same reason.
This is recommended:
char const *ptr = "some characters";
And the following is not recommended, as you might try to change the const data ptr
points to.
char *ptr = "some characters";
Good compilers should give warning in the second case.
GCC (4.3.4) does give warning:
prog.cpp:7: warning: deprecated conversion from string constant to ‘char*’
See yourself : http://www.ideone.com/8FqyZ
It's to tell the compiler to watch out for any code that may try and change the string. Although, you can be clever and still change the string, but normally it's to prevent accidental bugs in your code.
In C
both definitions below are perfectly legal and reasonable.
char const *ptr1 = "some characters";
char *ptr2 = "some characters";
In C
, a string literal is a value of type char[]
. In most uses it decays to a value of type char*
. Adding the const
modifier is, to many people, a good habit to get into: it gets the compiler to complain if the code attempts to change the string literal (which is undefined behaviour).
精彩评论