Hi i am a beginner in c language , learning about the "strcmp" function in the string.h library , when looking in the syntax of the function prototype i noticed this "while(*x)" loop can someone please explain how a while loop works with only one character without any operator (and another char to compare too) inside the parentheses to evaluate if any condition is true or false?? Bellow is the syntax for the "strcmp" function
#include <stdio.h>
// Function to implement strcmp function
int strcmp(const char *X, const char *Y)
{
while (*X)
{
// if characters differ, or end of the second string is
reached
if (*X != *Y) {
break;
}
// move to the next pair of characters
X ;
Y ;
}
// return the ASCII difference after converting `char*` to
`unsigned char*`
return *(const unsigned char*)X - *(const unsigned char*)Y;
}
// Implement `strcmp()` function in C
int main()
{
char *X = "Techie";
char *Y = "Tech";
int ret = strcmp(X, Y);
if (ret > 0) {
printf("%s", "X is greater than Y");
}
else if (ret < 0) {
printf("%s", "X is less than Y");
}
else {
printf("%s", "X is equal to Y");
}
return 0;
}
CodePudding user response:
In the C language, any non-zero value is treated as true
and zero as false
.
Because of this, you can use integer values as conditions.
while(*x)
will execute if the value referenced by x
is not equal zero.
CodePudding user response:
In C there is no such keyword as WHILE
. It seems you mean while
.
This while statement
while(*x)
is equivalent to
while( *x != 0 )
or that is the same
while( *x != '\0' )
That is the loop continues its iterations until the terminating zero character '\0'
of the string pointed to by the pointer x
is encountered.
Pay attention to that it is better to rewrite this while loop
while (*X)
{
// if characters differ, or end of the second string is reached
if (*X != *Y) {
break;
}
// move to the next pair of characters
X ;
Y ;
}
like
while ( *X && *X == *Y )
{
// move to the next pair of characters
X ;
Y ;
}
without the redundant if and break statements.