modest
modest

Reputation: 1457

'while' loop in string compare function loops more than necessary

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?

Upvotes: 2

Views: 2596

Answers (2)

Sam Aleksov
Sam Aleksov

Reputation: 1201

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!

Upvotes: 2

leonhart
leonhart

Reputation: 1201

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);

Upvotes: 8

Related Questions