C++ printf and cout
Well, for one thing, printf is a function and cout is a global (namespaced) variable. You wrote cout(), but that doesn't make sense, because you don't call cout itself. Here is an example:
cout << "Hello world" << endl;
You are actually making two function calls, both of them to overloads of operator<<(). This function is a binary operator; the first parameter is of type std::ostream& (an output stream) and the second parameter is of any type that can be output. It returns its first parameter, allowing this operator to be chained for outputting multiple values.
Unlike printf, cout (and other output streams) are type safe. When you do something like printf("%d",x);
, printf will treat x as an integer, no matter what type it actually is. This can be disastrously unsafe if you make a mistake. With cout, the types are all inferred at compile time, and there is no way to make this kind of mistake.
On the other hand, complex formatting is much easier to do with printf. You can format cout, but it is much more verbose, with lots of insertion of strange objects with names like precision and hex. Even then it doesn't have quite as many options as printf. Using cout is usually more verbose in general, even without formatting. So even though cout can do much of the formatting that printf can do, printf has hung onto the "best for easy formatting" niche, even in C++ code.
There are ways of building much better formatting libraries in C++. My favorite method is to use operator(), which looks like this:
print( "Hello, {0}, your user ID is {1}" )( name )( id );
I'm not sure if anyone has standardized a good formatting library. I have seen it done with the % operator, but I dislike both the precedence and the readability of that method. We rolled our own.
Last updated