Skip to content

Commit

Permalink
Update strncmp.c
Browse files Browse the repository at this point in the history
Increased the accuracy of the comment description, and removed the " != '\0' " part of the while test. Comparing two characters for equality doesn't require seeing if their comparison is not equal to null, it is the same as writing "while ((x == y) != 0)". If x and y are ints or any other datetype, the '==' check suffices when checking for a boolean value.
  • Loading branch information
sadeem-albir authored Mar 22, 2024
1 parent 7f3097e commit 40937ff
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions chapter_5/exercise_5_05/strncmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ int main(void)
// Return <0 if s<t, 0 if s==t, >0 if s>t *1
int strcmp_ptr(char *s, char *t, size_t n)
{
while ((*s == *t) != '\0' && --n)
while ((*s == *t) && --n)
{
if (*s == '\0')
return 0;
Expand All @@ -39,12 +39,12 @@ int strcmp_ptr(char *s, char *t, size_t n)
}

// If the s string contains more characters than t, then the t char will
// become '\0' before s char. If this happen then the s char will be >0 and
// t char will be 0, so the final result will be >0.
// become '\0' before s char. If this happen then the s char will be its ascii value and
// t char will be 0, so the final result will be s_ascii_value - 0.

// If the t string contains more character than s, then the s char will
// become '\0' before t char. If this happen then the s char will be <0 and
// t char will be 0, so the final result will be <0.
// become '\0' before t char. If this happen then the s char will be 0 and
// t char will be whatever ascii_value it's holding, so the final result will be 0 - t_ascii_value.

return *s - *t;
}

0 comments on commit 40937ff

Please sign in to comment.