2

The strcmp_kr function is based on the string compare function from K&R.

#include<stdio.h>
#include<string.h>

int strcmp_kr (char *s, char *d) {

int i=0;

    while ((s[i] == d[i])) {
        printf("Entered while loop\n");
        if (s[i] == '\0')
            return 0;
        i++;
    }
    return s[i] - d[i];
}

int main() {

char s1[15];
char s2[15];
printf("Enter string no. 1:");
scanf("%s", s1);
printf("Enter string no. 2:");
scanf("%s", s2);
strcmp_kr(s1, s2) == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", strcmp_kr(s1, s2));

}

Output:

$ ./a.out

Enter string no. 1:modest

Enter string no. 2:modesy

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Entered while loop

Strings not equal by -5!

Question: Why is the while loop entering 10 times instead of 5?

1
  • Do not use scanf() without specifying field width otherwise it has a risk of buffer overrun, it doesn't exactly concern your problem though. I mentioned it as a precaution :) Commented Jul 10, 2013 at 5:20

2 Answers 2

8
strcmp_kr(s1, s2) == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", strcmp_kr(s1, s2));

you have called strcmp_kr(s1, s2) twice ,first in the condition, and second in the printf since your condition is false, so you get 10 times of the print message.

to avoid this, store the return value in a variable like

int rtn = strcmp_kr(s1, s2);
rtn == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", rtn);
Sign up to request clarification or add additional context in comments.

Comments

2

you're calling the function twice:

strcmp_kr(s1, s2) == 0 ? printf("Strings equal!\n") : \ printf("Strings not equal by %d!\n", strcmp_kr(s1, s2));

The first call evaluates to false and calls the function again.

Cheers!

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.