Experiment 15: Simple Expressions


Unlike most languages, C++ performs I/O through the use of expressions. To illustrate, the general form of an output expression is

   outputStream << Expression
where outputStream is the name of an ostream (a type defined in the iostream library), << is the output or extraction operator, and Expression is any valid C++ expression.

When execution reaches such an expression, Expression is evaluated and its value is inserted onto outputStream. For example, in the output statement

   cout << 2 + 3 ;
cout is the name of an ostream object defined in the iostream library that connects an executing program to an interactive output device (e.g., a computer monitor, a window, etc.). The expression 2 + 3 is evaluated and its value 5 is inserted onto cout, and since cout is a stream, the value "flows" through it to your screen.

Does this indicate that the << operator is higher or lower in precedence then the + operator? Why?



We have also seen that output expressions can be chained together, as follows:

   cout << 1 << 3 << 5 << endl;
What is displayed? (Use your source program, if necessary.)



Does this indicate that the << operator is left, or right associative? Explain why.



In order for the the generalized output expression given above to be correct, the value produced by the << operator must be its left operand (the outputStream). That is, our generalized expression says that the left operand of << must be an outputStream, and since an expression like

   cout << 1 << 3 << 5 << endl;
inserts 1, then 3, and then 5 into cout, the first subexpression
   cout << 1 << 3 << 5 << endl;
must produce cout as its result, in order for the next subexpression to insert its value into cout
     resultA << 3 << 5 << endl;
and that subexpression must in turn produce cout as its value, in order for the next subexpression to insert its value into cout:
           resultB << 5 << endl;
and so on down the chain of operators. This is important because cout is not the only ostream into which we can insert values, as we shall see in a future exercise.

The input/extraction operator has the same precedence and associativity as the output/insertion operator, and the value it produces is its left operand (an inputStream), to permit the chaining of input expressions:

  cin >> x >> y >> z;
You should now understand that the << and >> operators are truly operators, that produce a value as their result. In the case of <<, the value produced is the ostream that was its left operand, which is usually cout. In the case of >>, the value produced is the istream that was its left operand, which is usually cin. You should also understand that each of these operators is left-associative, and how this associativity is used by chained input or output expressions.


Back to the Experiment List

Forward to This Week's Projects


Copyright 1998 by Joel C. Adams. All rights reserved.