C Language

Merrily Down the Streams

The new C++ "streams" I/O package provides a safer way to do I/O because the compiler will automatically generate a valid format based on the type of data being read or written. In most cases, using streams is also simpler than calling the standard C I/O functions. For both safety and convenience, where possible, use stream I/O instead of the standard C library routines. The following example shows how to write a label and value to the standard output:

 cout << "x + y = " << x + y << '\n';

If x is 2 and y is 5, the output is

 x + y = 7

Unfortunately, the C++ designers apparently couldn't stand the thought of introducing a useful new feature without building in at least one trap door. The following statement may look as innocent as the former, but it's not:

 cout << "x & y = " << x & y << '\n';

Because & has lower precedence than <, this expression is equivalent to

 (cout << "x & y = " << x) & (y << '\n');

The right way to code this statement is

 cout << "x & y = " << ( x & y ) << '\n';

This reinforces a C suggestion from Chapter 2 that also applies to C++: In a complex expression, use parentheses to explicitly define how the expression is evaluated. Be thankful for one thing, however. The C++ designers originally considered using < and > as the put and get operators - as if there weren't already enough confusion caused by the = and == operators!

by BrainBellupdated