I tried using following code sample given in Tour of C++ which uses nullptr to break loop over zero terminated string. However, my sample program doesn't seem to stop in the loop.
Excerpt from the book:
first version of code from book:
```
int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
for (; p!=nullptr; ++p)
if (∗p==x)
++count;
return count;
}
```
second simplified version
```int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to
// nothing)
{
int count = 0;
while (p) {
if (*p==x)
++count;
++p;
}
return count;
}```
statement following code in the book: The while-statement executes until its condition becomes false. A test of a pointer (e.g., while (p)) is equivalent to comparing the pointer to the null pointer (e.g., while (p!=nullptr)).
My program using same structure:
char name[] = "ABCD";
char *p = name;
int count = 0;
int loopc = 0;
while (p)
{
loopc++;
if(*p == '\0')
cout << "zero found\n";
else
cout << *p << "\n";
//emergency stop
if (loopc == 12)
break;
p++;
}
expected:
Should stop after printing name.
actual:
A
B
C
D
zero found
zero found
zero found
zero found
zero found
zero found
zero found
zero found
Thanks for all the useful comments.
It seems the author had given wrong example in the earlier edition (1st) which was later corrected in second edition released in 2018.
Corrected version from new edition:
int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
for (; *p!=0; ++p)
if (∗p==x)
++count;
return count;
}