1. What does while (*str++);
do?
It checks if the character pointed to by str
is not zero ('\0'
) and advances the pointer by one each time
In short: it moves str
forward until it reaches the end of the string
2. How does it work?
*str++
means: First, use the value pointed to by str
(the current character)
Then increment str
to point to the next character
The loop continues until it encounters the null terminator '\0'
, where the condition becomes false
3. Is while (*str++);
different from while (*str++ != '\0');
?
Functionally, both achieve the same result
while (*str++);
relies on the fact that the condition is false (zero) when it encounters '\0'
while (*str++ != '\0');
makes the check explicit, but is slightly more verbose
Example demonstration:
#include <stdio.h>
int main() {
char str[] = "hello";
char *p = str;
while (*p++)
printf("Moving over: %c\n", *(p - 1));
printf("Reached the end of string.\n");
return 0;
}