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

4
  • 3
    Here, have a look at what strcmp does. Commented Feb 17, 2014 at 19:18
  • 2
    Because the strings are equal, strcmp returns 0. man strcmp! Commented Feb 17, 2014 at 19:18
  • Removed C++ tag and removed C language reference from title. Commented Feb 17, 2014 at 19:28
  • Yaa..Got that .silly question to ask .:P. Commented Feb 18, 2014 at 16:17

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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  

Comments

2

strcmp on success returns 0. Hence if will fail.

Change if statement as,

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

Comments

2

strcmp returns 0 if the two strings compare equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.