Hacker News new | ask | show | jobs
by Danieru 4249 days ago
That series of strcat's caught my eye as bad practice. Fine in this case since the destination string is short but horrible in general. Every single one of those calls needs to iterate over the entire existing string to find the string size. The code could be much cleaner with a small macro hiding the incrementation and the casts.
3 comments

Basically it's an O(n^2) algorithm... well-known story about that here:

http://www.joelonsoftware.com/articles/fog0000000319.html

The design of strcat() itself is partially to blame for this - the return value could've been more useful, like the number of characters in the resulting string or a pointer to the end of the appended string so it could be used to chain concatenations, but instead they chose to return the exact same pointer that was passed in as the source.

Yeah- implicit concatenation + snprintf seems like the way to go. Although you'd have to calculate a length, I suspect avoiding that is the primary virtue of this approach.
A sufficiently smart compiler could optimize a string of strcat calls to remove the redundant length finding. I have no idea if real compilers actually would....
Java does, for the "+" operator.
Oh yes, nice example! So there's precedent for C compilers doing something similar.