Thursday, April 9, 2009

Why doesn't \% print a literal % with printf?

Answer: Backslash sequences are interpreted by the compiler (\n, \", \0, etc.), and \% is not one of the recognized backslash sequences. It's not clear what the compiler would do with a \% sequence -- it might delete it, or replace it with a single %, or perhaps pass it through as \ %. But it's printf's behavior we're trying to change, and printf's special character is %. So it's a %-sequence we should be looking for to print a literal %, and printf defines the one we want as %%.

No comments: