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

White Wolf wolof at freemail.hu
Thu Oct 28 15:34:35 EDT 2004


Gregory Haley wrote:
[SNIP]
>> It's easy to use, and the resulting code is clear.
>> 
>> It's highly efficient, since it writes directly to a character array.
> 
> At the risk of having abuse and ridicule rain down on my
> head, I have to confess, I've never gotten sprintf to work
> for me right out of the box.  I'm sure this has more to do
> with the route I took to c++, which involved only a
> smattering of c here and there, but I don't agree that it's
> either easy to use or produces clear code.  Ironically, it is
> not until reading this that I finally understood as well as I could
> this tool. 
> 
> Possibly, if I had been writting in C for years and years, I
> might find that the string formatters in the next item look
> ugly and non-intuitive.  Since I'm responsible for the review
> of Item 3, I'll stop here.
> 
> Once you work out the logic, it is very efficient.

I completely agree.  I also wanted to challenge that "easy to use" part.
Easy to use for a C programmer.  I still have to lookup non-obvious things
every time I use it.  In addition altough it is part of the C++ standard but
many (if not every) implementation has non-standard extensions, not
necessarily flagged clearly as such in the documentation.

But the worse is in the code of others I have seen in the past 5 years or
so.  Since int and long are the same size on many 32bit architectures today,
people keep printing longs as ints.  So they use %d instead of %ld.  When
compiling with g++ this causes tons of warnings.  Then you tell to people to
fix it, the next time you get half of the warnings.  Why?  Because the
syntax is absolutely unintuitive for most, so people have changed %d into
%dl instead of %ld.  I think if I wanted to I could still find numbers in
the logs printed as 0l...

So I disagree that it is easy to use for the masses.  The easiness comes
only with practice which can be true for any tool.  It looks simple once it
is written, more simple than stream output, since the text remains at one
place (the format string) so it is more readable what you want to say.  With
iostreams the text gets scattered.

Attila aka WW





More information about the Effective-cpp mailing list