LWN.net Logo

snprintf() confusion

snprintf() confusion

Posted Feb 7, 2004 10:00 UTC (Sat) by ThePythonicCow (subscriber, #11308)
In reply to: snprintf() confusion by giraffedata
Parent article: snprintf() confusion

    I doubt the wasted computation entered into the decision.
Hmmmm ... I feel we are both guessing slightly off. You're likely right it wasn't an explicit decision to save cpu cycles. But the analogy with printf is fragile as well - it's not like printf has a choice of two possible lengths to choose from. It writes whatever it has format for, and counts it all (or SEGV's trying).

Your last words:

    is actually quite unconventional
might come closest to the mark. Something about the modern value just seems odd. The early snprintf creators perhaps didn't even consider that choice of return value as an alternative.


(Log in to post comments)

snprintf() confusion

Posted Feb 7, 2004 18:09 UTC (Sat) by giraffedata (subscriber, #1954) [Link]

it's not like printf has a choice of two possible lengths to choose from. It writes whatever it has format for, and counts it all (or SEGV's trying).

OK, I see in the printf case, a partial write isn't practical. But it doesn't really weaken the argument that printf is an I/O routine, and so it is natural to follow the pattern of write() and fwrite() and return the number of bytes written.

The leap from there to snprintf() is a lot more obvious when you include the sprintf() step. sprintf(), derived from printf(), quite naturally returns the number of characters formatted, just like printf(). And it's a very useful value, too. snprintf() was derived from sprintf(), and merely adds a constraint on the length; If you're going to drop it in to replace a dangerous sprintf(), you clearly want it to do the same as sprintf() and return the number of characters formatted.

snprintf() confusion

Posted Feb 7, 2004 18:56 UTC (Sat) by ThePythonicCow (subscriber, #11308) [Link]

Yeah - that makes sense.

Copyright © 2008, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds