Solution for Exercise 19-14

ex1914

#include <stdio.h>

int main()
{
    char sample[] = "From whence cometh my help?\n";
    char *ps = sample;

    while(putchar(*ps++))
        ;
    return(0);
}

Notes

* That single while statement at Line 8 is how you can use a pointer to display a string.

* As a review, here is the while loop from my solution to Exercise 19-13:

What's the difference between the item in the while loop's evaluation and the putchar() function's argument? Both items are essentially the same, a character in a string. The main difference is the increment operator in the putchar() function. So you could modify the two statements like this:

As I wrote in the book, the putchar() function returns the value displayed, which would be the \0 when the end of the string is encountered. So the while loop terminates as it did before.

The sole ps++ statement in the loop merely increments the pointer. That, too, can be placed inside the while loop's evaluation. Even though the order of precedence places the ++ operator higher than * (pointer), the character at memory location ps is read before the memory location is incremented. The end effect, as shown in the code listing at the top of this page, is that the while loop becomes one empty statement: