Home > Software engineering >  How does the language differentiate from format code like %s and actual string "%s"?
How does the language differentiate from format code like %s and actual string "%s"?

Time:12-19

For example, in the code printf("hello world, %s", variable) it would print "hello world stack", but what if I actually wanted to print "hello world %s"?

How does the computer/language know the difference? From my perspective, it seems like the format code (%s) is left inside the quotes, therefore it should print the whole thing as a string.

CodePudding user response:

You are right about the string part - a format string is just any ordinary string, and the '%' is stored in the memory just as a percentage sign. In fact, if you feed the very same string to puts, it just prints %s as is.

However, the interpretation of the format string of printf-family functions is done at runtime: it actually scans the format string character by character, and whenever it encounters a '%', it parses the neighbouring few chars as a format specifier, and formats the corresponding parameter.

To print a literal '%' however, you just use %% and printf will know to output a percentage sign.

You can read the glibc implementation of printf-family functions here. Or a much tidier musl implementation of strftime here.

CodePudding user response:

You can escape the '%' character with another '%':

printf("Hello: %%s\r\n");

will print "Hello: %s "

CodePudding user response:

You can use printf("%%s") to print "%s", but you should really only use the pattern string for patterns. It would be better to do something like printf("%s", "%s") - that is, the string you want to print is the second, it will not interpret "%s", "%d", or any other pattern so you don't have to worry about how to express them.

It's also kind of useless and confusing for a single string, so better to use puts("%s").

  •  Tags:  
  • c
  • Related