tags:

views:

238

answers:

3

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 that?

Whereas this onedoesn't compile (which makes sense):

int str(const int i_)
{
  i_ = 0;
  return 0;
}
+12  A: 

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_)
James McNellis
+16  A: 

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;
}
pmg
thanks. that was clear.
ShaChris23
More importantly, this pointer was taken by *value*, the original function does absolutely nothing!
rlbond
rlbond makes an important point, in C arguments are passed by value so if the function modifies its arguments, no change is seen outside of that function.
Artelius
+7  A: 

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;
Artelius
and use `const char * const str;` to make everything constant, or is it `char const * const str` ? another inconsistency in C... (actually, the 2 declarations are equivalent)
Adrien Plisson