Main Content

printf - a flawed but useful function

Archive - Originally posted on "The Horse's Mouth" - 2006-02-22 06:34:48 - Graham Ellis

Many languages have printf statements ... and yet from a computer scientist's viewpoint, printf is a flawed function. In order for code to be clean and re-usable, functions should be designed to perform a single task. Alas, printf performs two tasks - it both formats the information that's entered in to it AND it then sends that information to an output stream.

What's the better alternative? Where you have printf, you probably have sprintf as well and that's a much better function - it just returns you the formatted string. So I'm advocating that, in Perl for example, you should write:

$tstring = sprintf("%02d:%02d",$hour,$min);
print ("Ths time of this record was $tstring\n");