Is there any difference between those 2 expressions when it comes to check whether or not we come to the end of the string?
while(str[i] != '\0')
and
while (str[i])
where str has type char* and i is an integer.
CodePudding user response:
In fact there is no difference. Any expression that evaluates to a non-zero value is considered as a logical true expression. And an expression that evaluates to zero is considered as a logical false expression.
From the C Standard (6.8.5 Iteration statements)
4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.1
Pay attention to that in C an expression with an equality operator has as value either 1 or 0.
So the expression str[i] != '\0' yields 1 (non-zero value) if the relation is true or -0 otherwise.
In C the type of such an expression is bool and its value is either true or false.
From the C 14 Standard (4.12 Boolean conversions)
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
CodePudding user response:
Look at example
#include <stdio.h>
int main()
{
int i;
char *a = "Hello word";
// above declaration equivalent with this:
// char a[] = {'H','e','l','l','o',' ','w','o','r','d','\0'};
i = 0;
while(a[i] != '\0') { // looping until null char founded
printf("%c", a[i]);
i ;
}
printf("\n");
i = 0;
while(a[i]) { // looping while `null` is not founded
printf("%c", a[i]);
i ;
}
return 0;
}
Result:
Hello word
Hello word
