C: const vs no const ..how come this compiles?
I have a simple C function which I declare as:
int strLen(const char* str_)
{
str_ = (char*) 0;
return 0;
}
I was very surprised that that compiles! Why is th开发者_JAVA百科at?
Whereas this onedoesn't compile (which makes sense):
int str(const int i_)
{
i_ = 0;
return 0;
}
Because const char* str_
says that str_ is a pointer to const characters.
You can change str_ itself, but not what it points to.
int strLen(const char* str_)
{
str_ = (char*) 0; /* allowed */
str_[0] = '\0'; /* not allowed */
return 0;
}
In the first one, you are changing what the pointer str_
points to; the pointer str_
is not const; it just points to const data. You can make the pointer const as follows:
int strLen(const char* const str_)
This follows the conventions of C declarations,
char *str;
means that *str
will give you a char
(or in other words, str
is a pointer-to-a-char). Similarly,
const char *str;
means that *str
will give you a const char
, or in other words, str
is a pointer-to-a-constant-char. So, you are not allowed to change *str
, but you may change str
.
If you want to make str
itself const
, use the following syntax:
char *const str;
精彩评论