3

I'm learning the C language.

My question is: Why is the param of strlen a "const" ?

size_t strlen(const char * string);

I'm thinking it's because string is an address so it doesn't change after initialization. If this is right, does that mean every time you build a function using a pointer as a param, it should be set to a constant ?

Like if I decide to build a function that sets an int variable to its double, should it be defined as:

void timesTwo(const int *num)
{
    *num *= 2;
}

or

void timesTwo(int *num)
{
    *num *= 2;
}

Or does it make no difference at all ?

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
conradkleinespel
  • 6,560
  • 10
  • 51
  • 87

3 Answers3

8

C string is a pointer to a zero-terminated sequence of characters. const in front of char * indicates to the compiler and to the programmer calling the function that strlen is not going to modify the data pointed to by the string pointer.

This point is easier to understand when you look at strcpy:

char * strcpy ( char * destination, const char * source );

its second argument is const, but its first argument is not. This tells the programmer that the data pointed to by the first pointer may be modified by the function, while the data pointed to by the second pointer will remain constant upon return from strcpy.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

The parameter to strlen function is a pointer to a const because the function is not expected to change what the pointer points to - it is only expected to do something with the string without altering it.

In your function 'timesTwo', if you intend to change the value that 'num' points to, you should not pass it in as a pointer-to-const. So, use the second example.

Specksynder
  • 813
  • 9
  • 20
4

Basically, the function is promising that it will not modify the contents of of the input string through that pointer; it says that the expression *string may not be written to.

Here are the various permutations of the const qualifier:

const char *s;            // s may be modified, *s may not be modified
char const *s;            // same as above
char * const s;           // s may not be modified, *s may be modified
const char * const s;     // neither s nor *s may be modified
char const * const s;     // same as above
John Bode
  • 119,563
  • 19
  • 122
  • 198