Article 67NPS CodeSOD: String Formatting

CodeSOD: String Formatting

by
Remy Porter
from The Daily WTF on (#67NPS)

There are certain things I can't remember for the life of me. For example, as per yesterday, the number of nanoseconds in a millisecond.

One of the other is the specific little formatting tokens for printf. I use it all the time, but the various riffs on %d escape my brain faster than I can put them in. Even just getting the hex values dumped for debugging requires a search. But I at least do that search, unlike Mike's co-worker.

#if defined COMPILER_GCC printf("configuration: " CONFIG_STRING "\n");#elif defined COMPILER_XYZ /* XYZ doesn't seem to support concatenation like that */ printf("configuration: "); printf( CONFIG_STRING ); printf( "\n");#endif

Now, an interesting quirk of C's translation process is that, at least in most compilers, adjacent string literals get concatenated into a single string. So the first branch here makes sense, though you have to be used to C idioms. That COMPILER_XYZ doesn't support it is odd and suspicious, but hardly shocking.

But the WTF, of course, is that printf already does what the developer wants in a way that the compilers don't care about. This whole block could be replaced with: printf("configuration: %s\n", CONFIG_STRING). It's what the f in printf stands for: format! It's the entire reason the function exists. Based on the comments, it seems like the developer wrote the GCC branch as the only branch, discovered a compiler error, and instead of spending the five seconds thinking about what printf does, they just sorta hacked around it. Arguably, the GCC version "formats" at compile time, so is probably faster, but we're looking at dumping configuration info for what I suspect is debugging/logging purposes- performance isn't a concern.

It's like watching this video in microcosm.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments