hitesh
hitesh

Reputation: 378

comparing character array and character pointer using strcmp

int main(void) {
    char s[] = "ab";
    char *s1 = "ab";

    if(strcmp(s, s1))
        printf("%d", 24);
    else
        printf("%d", 23);

    return EXIT_SUCCESS;
}

Why it is giving 23 answer?

Upvotes: 2

Views: 3354

Answers (4)

haccks
haccks

Reputation: 106112

This is because strcmp returns 0 if strings are equal. 0 is treated as false in C.

strcmp(string1, string2)

Return Value

if Return value < 0 then it indicates string1 is less than string2

if Return value > 0 then it indicates string2 is less than string1

if Return value = 0 then it indicates string1 is equal to string2  

Upvotes: 4

user2033018
user2033018

Reputation:

strcmp returns 0 if the two strings compare equal.

Upvotes: 2

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12688

strcmp on success returns 0. Hence if will fail.

Change if statement as,

if(strcmp(s , s1) == 0)

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

strcmp returns 0 if the given strings are equal, as in this case. 0 is converted to false, so the else block is executed, printing 23.

Upvotes: 4

Related Questions