kkr
kkr

Reputation: 61

Why do string functions have some parameters as const char *( pointers to constant characters)?

Strings(character arrays) can be modified in C but string literals can't be modified. But why do string functions like strlen(const char *str) have a pointer to a constant characters?

Upvotes: 1

Views: 721

Answers (4)

jamesdlin
jamesdlin

Reputation: 89965

const T* p means that the memory that p points to cannot be modified via the variable p. It represents a promise that p will not be used to modify the memory pointed to. It does not mean that the p points to memory that can never be modified.

It's always safe to convert from a T* to a const T*:

T value;
T* q = &value; // Not const.
const T* p = q; // No cast necessary.
p = &value; // No cast necessary here either.

Consequently, if a string function does not mutate its arguments, there is no harm in declaring its parameters as const char*:

const char* s = "string literal";
strlen(s); // This is legal.

char buf[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
strlen(buf); // This is legal too.

However, if the parameter instead were declared as just char*, then you would not be able to pass const char* to it.

 void foo(char* s);

 const char* s = "string literal";
 foo(s); // This will fail to compile.

Therefore it is advantageous to remember to qualify pointer arguments with const if possible, and doing so documents that the function promises not to mutate the pointee.

Upvotes: 2

user4983149
user4983149

Reputation:

strlen(const char *str) have a pointer to constant characters because it'll take the input *str as read-only string, and then perform the calculation and return the value without modifying the original string because it in order to count the length of the string, it doesn't need to modify the string in the memory.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

Because they do not modify (and do not need to modify) their argument strings. That's what that const means.

If strlen's argument were declared as char * (no const), you wouldn't be able to use strlen to determine the length of a constant string. For example

size_t my_own_strlen(char *str) { /* whatever */ }

const char hello[] = "Hello";

size_t l1 = my_own_strlen(hello); // Error: cannot convert `const char *` to `char *`
size_t l2 = strlen(hello);        // OK

Declaring that argument as const char * makes strlen applicable to both constant and non-constant strings.

Upvotes: 3

MrMobster
MrMobster

Reputation: 1972

It simply means that the function will not modify the data the pointer points to. Gives you some type safety and the compiler opportunity to optimise.

Upvotes: 1

Related Questions