I l@ve RuBoard Previous Section Next Section

9.9 Answers to Chapter Questions

Answer 9-1:The programmer went to a lot of trouble to explain that the for loop did nothing (except increment the index). However, there is no semicolon at the end of the for. C++ keeps reading until it sees a statement (in this case return(index)) and puts it in the for loop. Example 9-11 contains a correctly written version of the program.

Example 9-11. length/rlen.cpp
int  length(char string[])
{
    int index;      // index into the string 

    /*
     * Loop until we reach the end of string character
     */
    for (index = 0; string[index] != '\0'; ++index)
        /* do nothing */ ;
    return (index);
}
    I l@ve RuBoard Previous Section Next Section