Wednesday, December 24, 2014

Using printf in C++ Instead of cout

If you study C++ from textbooks you will see the cout function used to print.  Later you might be surprised to see people using the older printf function from the C programming language within C++ programs.  When I first ran across this practice I asked why the older function was used and I was told that it was more efficient.

It is hard to find supporting evidence for this claim, so here is a link to "In defense of printf" by Kenny Kerr, which has this quote: "...cout has a serious performance problem."  The author presents a chart of performance measurement.

I remember the book Efficient C++: Performance Programming Techniques by Bulka & Mayhew recommending printf over cout, but I have lost my copy of this book and cannot verify my recollection.

So if you see someone using printf in a C++ program, be aware that it is an acceptable practice.  For a student's purposes, cout is fine.

Robert

2 comments:

  1. Speaking of C++, betcha can't guess where Bjarne Stroustrup works nowadays...?

    http://www.stroustrup.com/

    ReplyDelete
  2. I went to the website you mentioned. Here's what Stroustrup said: "I'm a Managing Director in the technology division of Morgan Stanley in New York City and a Visiting Professor in Computer Science at Columbia University." Very cool!

    ReplyDelete

Comments require my approval before they appear. Be patient. It will take a day or two for your comment to appear.