Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 906
modest Avatar asked Jun 04 '26 23:06

modest


1 Answers

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);
like image 166
leonhart Avatar answered Jun 06 '26 18:06

leonhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!