What is the difference between printf() and cout in C++?
More differences: "printf" returns an integer value (equal to the number of characters printed) and "cout" does not return anything
And.
cout << "y = " << 7;
is not atomic.
printf("%s = %d", "y", 7);
is atomic.
cout performs typechecking, printf doesn't.
There's no iostream equivalent of "% d"
TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.
I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.
In said task, we had to write some config to RAM. Something like:
coffee=hot
sugar=none
milk=breast
mac=AA:BB:CC:DD:EE:FF
Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)
C program:
char coffee[10], sugar[10], milk[10];
unsigned char mac[6];
/* Initialize those things here. */
FILE * f = fopen("a.txt", "wt");
fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);
fclose(f);
C++ program:
//Everything else is identical except:
std::ofstream f("a.txt", std::ios::out);
f << "coffee=" << coffee << "\n";
f << "sugar=" << sugar << "\n";
f << "milk=" << milk << "\n";
f << "mac=" << (int)mac[0] << ":"
<< (int)mac[1] << ":"
<< (int)mac[2] << ":"
<< (int)mac[3] << ":"
<< (int)mac[4] << ":"
<< (int)mac[5] << endl;
f.close();
I did my best to polish them before I looped them both 100,000 times. Here are the results:
C program:
real 0m 8.01s
user 0m 2.37s
sys 0m 5.58s
C++ program:
real 0m 6.07s
user 0m 3.18s
sys 0m 2.84s
Object file size:
C - 2,092 bytes
C++ - 3,272 bytes
Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.
Remeber, YMMV.
printf
is a function whereas cout
is a variable.
And I quote:
In high level terms, the main differences are type safety (cstdio doesn't have it), performance (most iostreams implementations are slower than the cstdio ones) and extensibility (iostreams allows custom output targets and seamless output of user defined types).
I'd like to point out that if you want to play with threads in C++, if you use cout
you can get some interesting results.
Consider this code:
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void task(int taskNum, string msg) {
for (int i = 0; i < 5; ++i) {
cout << "#" << taskNum << ": " << msg << endl;
}
}
int main() {
thread t1(task, 1, "AAA");
thread t2(task, 2, "BBB");
t1.join();
t2.join();
return 0;
}
// g++ ./thread.cpp -o thread.out -ansi -pedantic -pthread -std=c++0x
Now, the output comes all shuffled. It can yield different results too, try executing several times:
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
##12:: ABABAB
You can use printf
to get it right, or you can use mutex
.
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
Have fun!
I would like say that extensibility lack of printf
is not entirely true:
In C, it is true. But in C, there are no real classes.
In C++, it is possible to overload cast operator, so, overloading a char*
operator and using printf
like this:
Foo bar;
...;
printf("%s",bar);
can be possible, if Foo overload the good operator. Or if you made a good method. In short, printf
is as extensible as cout
for me.
Technical argument I can see for C++ streams (in general... not only cout.) are:
Typesafety. (And, by the way, if I want to print a single '\n'
I use putchar('\n')
... I will not use a nuke-bomb to kill an insect.).
Simpler to learn. (no "complicated" parameters to learn, just to use <<
and >>
operators)
Work natively with std::string
(for printf
there is std::string::c_str()
, but for scanf
?)
For printf
I see:
Easier, or at least shorter (in term of characters written) complex formatting. Far more readable, for me (matter of taste I guess).
Better control of what the function made (Return how many characters where written and there is the %n
formatter: "Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored." (from printf - C++ Reference)
Better debugging possibilities. For same reason as last argument.
My personal preferences go to printf
(and scanf
) functions, mainly because I love short lines, and because I don't think type problems on printing text are really hard to avoid.
The only thing I deplore with C-style functions is that std::string
is not supported. We have to go through a char*
before giving it to printf
(with the std::string::c_str()
if we want to read, but how to write?)