Chapter 6

1: Consider the following two code fragments for counting spaces and newlines:
// Version 1
while (cin.get(ch))    // quit on eof
{
      if (ch == ' ')
             spaces++;
      if (ch == '\n')
            newlines++;
}
// Version 2
while (cin.get(ch))    // quit on eof
{
      if (ch == ' ')
            spaces++;
      else if (ch == '\n')
            newlines++;
}

What advantages, if any, does the second form have over the first?

A1: Both versions give the same answers, but the if else version is more efficient. Consider what happens, for example, when ch is a space. Version 1, after incrementing spaces, tests to see whether the character is a newline. This wastes time because the program already has established that ch is a space and hence could not be a newline. Version 2, in the same situation, skips the ...

Get C++ Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.