Davut Özcan
Davut Özcan

Reputation: 109

Why does not used constant pointer at strcmp in cstring.h

In cstring.h file there exists a function:

int strcmp ( const char *s1, const char *s2 ), but why only the data is constant, isn't it more safe to make both pointer and data constant.In my opinion the correct version of function should be like:

int strcmp ( const char * const s1, const char * const s2 )

Upvotes: 2

Views: 461

Answers (3)

James Kanze
James Kanze

Reputation: 153977

As others have pointed out, the top level const is ignored in the declaration; the most frequent convention I've seen has been to forbid it.

It does have meaning in the definition. But the most frequent implementation of strcmp is something like:

int
strcmp( char const* s1, char const* s2 )
{
    while ( *s1 != '\0' && *s2 != '\0' && *s1 == *s2 ) {
        ++ s1;
        ++ s2;
    }
    return (unsigned char)( *s1 ) - (unsigned char)( *s2 );
}

The parameters aren't const.

Upvotes: 2

fredoverflow
fredoverflow

Reputation: 263220

Top-level const modifiers of parameters are stripped from declarations, because they do not concern the client. Whether parameters are changed or not is an implementation detail. It is perfectly valid to declare a function as void f(int x) and then later define it as void f(const int x) (and vice versa).

In your example, even if s1 and s2 are modified inside strcmp, the client does not notice these modifications, because the pointers are passed by value (copied into the function). That is, if you call strcmp(a, b), then a and b will retain their values, even if str1 and str2 are changed.

Upvotes: 5

Kiril Kirov
Kiril Kirov

Reputation: 38173

It's not necessary. As the pointers are copied, I don't see how adding one more const makes anything safer?

And, most probably, the implementation changes the s1 and s2 pointers (probably in some loop, incrementing both pointers to compare each char, one by one).

Upvotes: 1

Related Questions