Should I use printf in my C++ code?
Solution 1
My students, who learn cin
and cout
first, then learn printf
later, overwhelmingly prefer printf
(or more usually fprintf
). I myself have found the printf
model sufficiently readable that I have ported it to other programming languages. So has Olivier Danvy, who has even made it type-safe.
Provided you have a compiler that is capable of type-checking calls to printf
, I see no reason not to use fprintf
and friends in C++.
Disclaimer: I am a terrible C++ programmer.
Solution 2
If you ever hope to i18n your program, stay away from iostreams. The problem is that it can be impossible to properly localize your strings if the sentence is composed of multiple fragments as is done with iostream.
Besides the issue of message fragments, you also have an issue of ordering. Consider a report that prints a student's name and their grade point average:
std::cout << name << " has a GPA of " << gpa << std::endl;
When you translate that to another language, the other language's grammar may need you to show the GPA before the name. AFAIK, iostreams has not way to reorder the interpolated values.
If you want the best of both worlds (type safety and being able to i18n), use Boost.Format.
Solution 3
I use printf because I hate the ugly <<cout<<
syntax.
Solution 4
Adaptability
Any attempt to printf
a non-POD results in undefined behaviour:
struct Foo {
virtual ~Foo() {}
operator float() const { return 0.f; }
};
printf ("%f", Foo());
std::string foo;
printf ("%s", foo);
The above printf-calls yield undefined behaviour. Your compiler may warn you indeed, but those warnings are not required by the standards and not possible for format strings only known at runtime.
IO-Streams:
std::cout << Foo();
std::string foo;
std::cout << foo;
Judge yourself.
Extensibility
struct Person {
string first_name;
string second_name;
};
std::ostream& operator<< (std::ostream &os, Person const& p) {
return os << p.first_name << ", " << p.second_name;
}
cout << p;
cout << p;
some_file << p;
C:
// inline everywhere
printf ("%s, %s", p.first_name, p.second_name);
printf ("%s, %s", p.first_name, p.second_name);
fprintf (some_file, "%s, %s", p.first_name, p.second_name);
or:
// re-usable (not common in my experience)
int person_fprint(FILE *f, const Person *p) {
return fprintf(f, "%s, %s", p->first_name, p->second_name);
}
int person_print(const Person *p) {
return person_fprint(stdout, p);
}
Person p;
....
person_print(&p);
Note how you have to take care of using the proper call arguments/signatures in C (e.g. person_fprint(stderr, ...
, person_fprint(myfile, ...
), where in C++, the "FILE
-argument" is automatically "derived" from the expression. A more exact equivalent of this derivation is actually more like this:
FILE *fout = stdout;
...
fprintf(fout, "Hello World!\n");
person_fprint(fout, ...);
fprintf(fout, "\n");
I18N
We reuse our Person definition:
cout << boost::format("Hello %1%") % p;
cout << boost::format("Na %1%, sei gegrüßt!") % p;
printf ("Hello %1$s, %2$s", p.first_name.c_str(), p.second_name.c_str());
printf ("Na %1$s, %2$s, sei gegrüßt!",
p.first_name.c_str(), p.second_name.c_str());
Judge yourself.
I find this less relevant as of today (2017). Maybe just a gut feeling, but I18N is not something that is done on a daily basis by your average C or C++ programmer. Plus, it's a pain in the a...natomy anyways.
Performance
- Have you measured the actual significance of printf performance? Are your bottleneck applications seriously so lazy that the output of computation results is a bottleneck? Are you sure you need C++ at all?
- The dreaded performance penalty is to satisfy those of you who want to use a mix of printf and cout. It is a feature, not a bug!
If you use iostreams consistently, you can
std::ios::sync_with_stdio(false);
and reap equal runtime with a good compiler:
#include <cstdio>
#include <iostream>
#include <ctime>
#include <fstream>
void ios_test (int n) {
for (int i=0; i<n; ++i) {
std::cout << "foobarfrob" << i;
}
}
void c_test (int n) {
for (int i=0; i<n; ++i) {
printf ("foobarfrob%d", i);
}
}
int main () {
const clock_t a_start = clock();
ios_test (10024*1024);
const double a = (clock() - a_start) / double(CLOCKS_PER_SEC);
const clock_t p_start = clock();
c_test (10024*1024);
const double p = (clock() - p_start) / double(CLOCKS_PER_SEC);
std::ios::sync_with_stdio(false);
const clock_t b_start = clock();
ios_test (10024*1024);
const double b = (clock() - b_start) / double(CLOCKS_PER_SEC);
std::ofstream res ("RESULTS");
res << "C ..............: " << p << " sec\n"
<< "C++, sync with C: " << a << " sec\n"
<< "C++, non-sync ..: " << b << " sec\n";
}
Results (g++ -O3 synced-unsynced-printf.cc
, ./a.out > /dev/null
, cat RESULTS
):
C ..............: 1.1 sec
C++, sync with C: 1.76 sec
C++, non-sync ..: 1.01 sec
Judge ... yourself.
No. You won't forbid me my printf.
You can haz a typesafe, I18N friendly printf in C++11, thanks to variadic templates. And you will be able to have them very, very performant using user-defined literals, i.e. it will be possible to write a fully static incarnation.
I have a proof of concept. Back then, support for C++11 was not as mature as it is now, but you get an idea.
Temporal Adaptability
// foo.h
...
struct Frob {
unsigned int x;
};
...
// alpha.cpp
... printf ("%u", frob.x); ...
// bravo.cpp
... printf ("%u", frob.x); ...
// charlie.cpp
... printf ("%u", frob.x); ...
// delta.cpp
... printf ("%u", frob.x); ...
Later, your data grows so big you must do
// foo.h
...
unsigned long long x;
...
It is an interesting exercise maintaining that and doing it bug-free. Especially when other, non-coupled projects use foo.h.
Other.
Bug Potential: There's a lot of space to commit mistakes with printf, especially when you throw user input bases strings in the mix (think of your I18N team). You must take care to properly escape every such format string, you must be sure to pass the right arguments, etc. etc..
IO-Streams make my binary bigger: If this is a more important issue than maintainability, code-quality, reuseability, then (after verifying the issue!) use printf.
Solution 5
Use boost::format. You get type safety, std::string support, printf like interface, ability to use cout, and lots of other good stuff. You won't go back.

Comments
-
Bob Dylan 5 months
I generally use
cout
andcerr
to write text to the console. However sometimes I find it easier to use the good oldprintf
statement. I use it when I need to format the output.One example of where I would use this is:
// Lets assume that I'm printing coordinates... printf("(%d,%d)\n", x, y); // To do the same thing as above using cout.... cout << "(" << x << "," << y << ")" << endl;
I know I can format output using
cout
but I already know how to use theprintf
. Is there any reason I shouldn't use theprintf
statement? -
Matt Joiner almost 13 yearsc libraries are very good quality, and easy to use. i agree that people shouldn't feel pressured to use c++ libraries.
-
Bob Dylan almost 13 yearsYeah I doubt this will work with a
printf
seeing as how templates didn't exist whenprintf
was invented. -
C. K. Young almost 13 yearsI use Java's
String.format
a lot. In C++, I use Boost.Format a lot, which is iostreams-friendly but also somewhatprintf
-compatible. -
GManNickG almost 13 yearsThat's the point. This is C++ code we're talking about, isn't it? Am I being down voted for having a true point? Can the down voters implement my function with
printf
? -
Bob Dylan almost 13 yearsYour not being downvoted because you have a true point, your being downvoted because your point is irrelevant. We know
printf
can't do this, it's not designed to. It's like saying, "Oh I bet you can't make a class in C". That point would be true as well because the language isn't designed to. -
GManNickG almost 13 yearsIt's hardly irrelevant. You're asking if you should use
printf
. For consistency, no. Streams will always work,printf
will not always work. Code that isn't consistent is ugly. What if I havecout
tee'd to also print to a log file? (And yes, all my projects do this!) Now you're just bypassing all that. There's more to think about than you saving keystrokes. -
Tim Crone almost 13 yearsGMan, I see where you are coming from, but I think the point may be better expressed as 'there is some value in using a consistent output operation'. The OP says he uses both cout and printf, so ultimately the question is whether he should be using just one - as you demonstrate, probably cout - or if it's okay to mix them up. I would say that it's okay, and hope that anyone who can program with cout isn't going to be befuddled by printf(), but I can see how other people might disagree.
-
GManNickG almost 13 yearsConsider my usage above. And in programming anyway, consistency is always a good thing.
-
Ferruccio almost 13 yearsThe ability to specify formatting parameters by position in boost::format() is great for localization.
-
Martin Beckett almost 13 yearsSo you have to write an overloaded << operator for T, rather than a print(T) function.
-
GManNickG almost 13 yearsRather than a
print(T, S)
function, actually. S is the output stream. No need for that withoperator<<
; it works on any ostream interface. -
ojrac almost 13 years+1 for the link. It's no 10 Commandments, but they sure have their heads on straight.
-
Matt Joiner almost 13 yearswhat better reason is there? :P
-
josesuero almost 13 yearsBut
boost::format
gives you such niceties as type safety.printf
just blows up. -
rpg almost 13 years*printf's lack of type safety is mitigated but not eliminated by compilers that check those calls, since using variables as format strings is a perfectly valid use case. e.g: i18n. This function can blow up in so many ways, it's not even funny. I just don't use it any more. We have access to perfectly good formatters such as boost::format or Qt::arg.
-
mingos almost 13 yearsAgreed here. It might seem annoying, but it's always a good idea to compile your code with as many restrictions from the compiler as possible. Enable all warnings, treat all warnings as if they were errors and, if possible, use electric fence + gdb as often as possible. But that's a general coding tip ;)
-
Norman Ramsey almost 13 years@rpg: I think the tradeoff is between readability and type safety. I think it's reasonable for different applications to make different tradeoffs. Once you're into i18n, readability is already halfway out the window anyway, and I agree type safety trumps printf in that situation. Interestingly, the way
boost::format
works is somewhat similar to the way Olivier Danvy's ML code works. -
Geoff almost 13 yearsIn my opinion while the Google C++ Style Guide is very good in many respects, the consistency trump they refer to is that of their own code. Remember that Google has been around for 10 years, and they value code consistency (a very good thing). The reason they aren't using printf is because people used it in previous incarnations of their code and they want to remain consistent. If this weren't the case I'm confident that they would be using streams instead.
-
Lazer over 12 years@Norman Ramsey: I see the
type safety problem
withprintf()
mentioned several times. What exactly is the type safety problem with printf()? -
Lazer over 12 years@Norman Ramsey: I am not sure what kind of problem can arise if the types are not checked. Can you please quote an example? I use
printf()
in C all the time. Never faced a problem. -
Norman Ramsey over 12 years@eSKay: It's very rare to have an issue in practice. But try
char *fmt = "%s %s"; printf(fmt, "hello");
orchar *fmt = "%s"; printf(fmt, main);
. -
bobobobo over 12 yearsInterestingly xCode IDE detects these things you've mentioned here (in its intellisense.)
-
bobobobo over 12 years"mixing
cout
andprintf
, while perfectly valid, is ugly" - the only ugly is thex << y << z
madness! -
bobobobo over 12 yearsTo printf an object, there's no problem with defining a member function
object.print( FILE* f )
. You can passstdout
,stderr
, or an already openFILE*
object to this function. -
Petruza about 11 yearsUsing C++ doesn't mean you have to object-orient everything, and particularly console printing is not something that really calls for the OO paradigm.
-
Sebastian Mach almost 11 yearsHuh?! You have precision control with iostreams, too.
-
Sebastian Mach over 10 yearsNot only have you to match the placeholders now, but also in future. See my updated post, section Temporal Adaptibility, and the other sections of course.
-
Sebastian Mach over 10 yearsWhy is printf better with spacing?
-
Sebastian Mach over 10 years@bobobobo: So you suggest that
printf(stdout, "Hello "); person.print(stdout); printf("! I see you've subscribed to the "); tags.print(stdout); printf("tags, nice!");
is less mad and more pretty thancout << "Hello " << person << "! I see you've subscribed to the " << tags << ", nice!";
? -
Sebastian Mach over 10 years@bobobobo: Apart from your other (orthogonal wrt topic) suggestion to introduce a pretty tight coupling on the object's public interface.
-
quantum over 10 years@phresnel cout << str1 << " " << str2 << '\n'; is a lot worse than printf("%s %s", str1, str2);
-
Sebastian Mach almost 10 yearsI am afraid that is not an extension to the
printf
interface. It would have been if you could now writeprintf("%[MyClass] is awesome, my_object")
. -
Sebastian Mach almost 10 years@Lazer: Buffer overruns, undefined behaviour, coredumps, off-by-one-errors, security-vulnerabilities. You may want to look up format string attack on wikipedia.
-
milleniumbug almost 10 years@phresnel I agree. This is only to say that it IS possible to print user-created objects with printf. It is a workaround, yes, but so is operator chaining workaround to lack of real vararg function capability in pre-C++11. C++ I/O library created now would be probably using initializer_list or variable-length template functions.
-
Sebastian Mach almost 10 yearsThough operator chaining is part of the iostreams interface, and the possibility to extend that interface is part of the interface, too, so it still holds true that iostreams are extensible, whereas printf is not. This is what I liked to point out :)
-
Sebastian Mach almost 10 yearsI agree on how probably variadic templates would now be used if a new io-library would become part of C++.
-
milleniumbug almost 10 years@phresnel Changed the wording in the answer.
-
Sebastian Mach almost 10 yearsI think it's better now :)
-
vitaut almost 10 yearsNice answer. Just want to add that there are alternatives to Boost Format that are several times faster while providing the same level of safety: github.com/vitaut/format and github.com/c42f/tinyformat
-
vitaut almost 10 yearsModern compilers diagnose mismatch between format specs and arguments.
-
necromancer over 9 yearsthank you - that is a very good explanation! @vitaut they cannot in general. for example, if the format spec itself is not a constant string literal but is coming from a configuration file. this is not a hypothetical example, in most commercial software, for 18n and for maintaining consistency of communication, most strings are not in-place literals but compartmentalized not always as literals.
-
Sebastian Mach over 9 years@agksmehx: Very nice example counter the reliability of format-string checking.
-
Sebastian Mach over 9 yearsI, too, never had a problem with my hammer. It's simple and robust, and I know what to expect when building a house with it.
-
milleniumbug over 9 yearsDownvoting without any comment is hardly constructive, as I have no opportunity to learn from my mistakes. Downvoter, could you explain the downvote?
-
mingos over 9 years@phresnel, that is correct: hammering nails using a hammer is by far the best choice of tools for the task. Allegedly, rocks work too, but not as well as hammers.
-
Sebastian Mach over 9 years@mingos: I prefer houses which are also held together with cement, screws, bolts (but a good hammer can do it). Lifting bricks to the third floor and sawing beams for the rooftop is a bit tough with a hammer, but it works :) I sometimes use C functions too, especially when talking with other software, but for the large part, I prefer when the compiler catches errors for me through strong and static typesafety. That way, if I change some piece somewhere, and do a complete recompile, I get errors everywhere which I can rely on (but that's just the tip of the iceberg of my reasoning).
-
mingos over 9 years@phresnel: Are you implying that a hammer (ie
printf
) is not a tool one should use because it's not good for screwing screws, sawing beams and lifting bricks? Ie, because it sucks at tasks it's not meant for? -
Sebastian Mach over 9 years@mingos: Exactly. But more seriously: You wrote "No reason at all", but actually there are plenty of reasons against it (the only thing I found
printf
better at was saving bytes). And while you may know how to use it right, many people do not (and I remember ungrateful debugging sessions like e.g. when there where triangles in a rasterizer which were flickering on screen, and by accident I found that a misused printf was at fault, at a totally remote place, not even in the same application code) -
mingos over 9 yearsA misuse of a function is also not a reason against using it at all :). I'm not advocating the use of
printf
overcout
(though others do - link in another answer to this question) and I agree there are cases wherecout
is clearly a more suitable option. However, I do firmly believe that usingcout
overprintf
just for the sake of it being "the C++ way" is no more than religious bs. -
Bill Weinman over 8 yearsYour code presumes that
pX
has an operator method for<<
. If I assume thatpX
has a type method for(char *)
I can useprintf()
with a(char *)
cast. That leaves no advantage forcout
. Personally, I very much dislike the overloaded meaning of the<<
operator, so I tend to preferprintf()
or other solutions. -
Code Abominator almost 6 yearscout only really works if you use a wrapper like tinyformat, otherwise every single cout line becomes a giant jumble of "set output flags, output"... ideally with "reset output flags" on the end. It gets really tedious after a while, and debugging even more so. Wrap or use printf IMO... which takes you back to a print-like situation.
-
Florian Castellane over 5 yearsIn that regard, I think that printf wouldn't be safer though.
-
Swift - Friday Pie over 4 yearscode not always bult in ide or on local system.It not always designed by same party. Format strings are platform dependant (because varables have different sizes on different platforms. In vs 2010 long is 64bit. In gcc it is 32bit. Boom, underrun). But I'm surprised on how few people know that there is standartized header with string literals for proper format strings.