[Effective-cpp] Item 2: The String Formatters of Manor Farm, Part 1: sprintf

Walter Vannini walterv at gbbservices.com
Wed Oct 27 23:18:26 EDT 2004


Item 2: The String Formatters of Manor Farm, Part 1: sprintf

The advantages and disadvantages of sprintf are discussed. The 
alternatives to using sprintf will be discussed in Item 3, the following 
item. Those alternatives are: snprintf, std::stringstream, 
std::strstream, and boost::lexical_cast.

The advantages of sprintf are:

It's part of the C++ standard.

It's easy to use, and the resulting code is clear.

It's highly efficient, since it writes directly to a character array.

The disadvantages are:

There is no length safety. There is no way to explicitly limit how much 
of the character array is used. This can and often does result in buffer 
overrun errors.

There is no type safety. Errors in the format specification are not 
caught at compile time. They're caught at run time, if you're lucky. 
Lint tools will catch many of these problems.

It is difficult to use in a template. An ugly example using 
specializations is provided.

For those wondering about "Manor Farm": in the novel "Animal Farm", the 
original name of the farm that became "Animal farm" was "Manor Farm".





More information about the Effective-cpp mailing list