find digit(cstr) will give 98k |
No, not quite. The function returns a pointer.
Before the loop there exist an array:
{ 'a', 'b', '9', '8', 'k', '\0' }
and the pointer
cstr
points to the first element of array (that contains the
a).
When you do call
find_digit(cstr)
the first time, it returns a pointer that points to the third element of the array (that contains the
9). The pointer points to somewhere other than memory address NULL.
Address NULL converts to false in condition and loop ends. Other than NULL converts to true and loop evaluates its body.
1 2 3 4 5 6 7
|
// cstr points to first element
while( find_digit(cstr) )
{
// cstr still points to first element
move_left(cstr);
// cstr still points to first element
}
|
On first iteration the condition is true and the move_left() executes.
The array after iteration:
{ 'b', '9', '8', 'k', '\0', '\0' }
On second iteration the condition is still true and the move_left() executes.
The array after iteration:
{ '9', '8', 'k', '\0', '\0', '\0' }
On 3rd iteration the condition is still true and the move_left() executes.
The array after iteration:
{ '8', 'k', '\0', '\0', '\0', '\0' }
On 4th iteration the condition is still true and the move_left() executes.
The array after iteration:
{ 'k', '\0', '\0', '\0', '\0', '\0' }
On 5th iteration the condition is false, the move_left() will not execute, and loop ends.
Array after loop:
{ 'k', '\0', '\0', '\0', '\0', '\0' }
1 2 3 4
|
*dst++ = *src;
// is same as
*dst = *src;
++dst;
|
vs.
1 2 3 4
|
*(++dst) = *src;
// is same as
++dst;
*dst = *src;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
char *dst = str;
for (char *src = str; *src; ++src) {
if (!isdigit(*src)) {
*dst++ = *src;
}
}
// is equivalent to
char *dst = str;
char *src = str;
while ( *src ) {
if (!isdigit(*src)) {
*dst++ = *src;
}
++src;
}
|