sivabudh
sivabudh

Reputation: 32635

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

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

int str(const int i_)
{
  i_ = 0;
  return 0;
}

Upvotes: 2

Views: 465

Answers (3)

Artelius
Artelius

Reputation: 49079

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;

Upvotes: 6

pmg
pmg

Reputation: 108968

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;
}

Upvotes: 15

James McNellis
James McNellis

Reputation: 355009

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_)

Upvotes: 11

Related Questions