C++ Programming/Operators/Chaining

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Chaining[edit | edit source]

std::cout << "The sum of " << a << " and " << b << " is " << sum << "\n";

The above line illustrates what is called chaining of insertion operators to print multiple expressions. How this works is as follows:

  1. The leftmost insertion operator takes as its operands, std::cout and the string "The sum of ", it prints the latter using the former, and returns a reference to the former.
  2. Now std::cout << a is evaluated. This prints the value contained in the location a, i.e. 123 and again returns std::cout.
  3. This process continues. Thus, successively the expressions std::cout << " and ", std::cout << b, std::cout << " is ", std::cout << " sum ", std::cout << "\n" are evaluated and the whole series of chained values is printed.