This page looks best with JavaScript enabled

Item-2 Compare <iostream> to <stdio.h>

 ·  ☕ 2 min read · 👀... views

Some tips about <iostream>

One advantage of <iostream> over <stdio.h> (which includes C-style scanf and printf) is that built-in types like int are read and written in the same manner as user-defined types like Rational:

1
2
3
4
5
int i;
Rational r;  // r is a user-defined rational number
...
cin >> i >> r;
cout << i << r;

So considering type safety and extensibility offered by the classes and functionas in the iosteam library, in general we should prefer <iostream> to <stdio.h>. In order for this code to compile, we mus define operator>> and operator<< for Rational type. A typical output routine may look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 clas Rational {
 public:
    Rational (int numerator = 0, int denominator = 1);
    ...
 private:
    int n, d;
 friend ostream& operator<<(ostream& s, const Rational& r);
 };

 ostream& operator<<(ostream& s, Rational& r) 
 {
     s << r.n << '/' << r.d;
     return s;
 }

There are some subtle points worth noting: operator<< is not a member function (explained in item 19) and the Rational object to be output is passed as a reference-to-const rather than as an object (see item 22).

Howerver, there are still very few situations where <stdio.h> may be more sensible to use:

  1. Some implementations of iostream operations are less efficient than corresponding C stream operations, so it may make sense for applications requiring extreme performance.
  2. During the course of standardization, iostream library was modified in some fundamental ways, so it may make sense for applications targeting at maximum portablility.
  3. Since classes of the iostream library have constructors while functions in <stdio.h> do not, when concerning about initialization order of static objects (see item 47) the standard C library may be more useful because you can always call it with impunity.

By the way

Technically speaking, the standardizatoin committee eliminated <iostream.h> in favor of <iostream> when they truncated the names of the other non-C standard header names, but chances are that most compilers support both of them. However, there is a subtle difference between them:

  1. when #include <iostream>, the iostream library is ensconced within the namespace std (item 28)
  2. when #include <iostream.h>, we get the same elements but they are at global scope

Thus we usually prefer using <iostream> for name conflicts consideration.

Share on
Support the author with