2

I've wanted to learn more about the C standard library, so I decided to implement printf using only the putchar function. I'd barely started when something odd happened. All I'd done was write a loop to print a verbatim copy of the format string, and then I realized that all the escape sequences, (\n, \t, etc.) had already been parsed and "properly" output.

Here's the minimal code:

int my_printf(const char* s){
    size_t i;
    char c;
    for (i = 0; (c = *(s + i)) != '\0'; ++i){
        putchar(c);
    }
    return 0;
}

int main(void){
    my_printf("Here\t1\n0\n");
    return 0;
}

I was expecting a literal Here\t1\n0\n to be output, but I instead got:

Here    1
0

Any idea why this happening? My first thought was that the compiler I'm using, (gcc), was trying to help by pre-analyzing the format string, but that seems odd, since it would cause a lot of problems, since it would break any char array. So, does anyone know why this is happening? And is this behavior defined in the standard? Thank you for any help!

Edit: As mafso stated in their answer, the replacements are done at compile time, and it is standard. Section 5.1.1.2.1.5 of the standard has the actual text.

doniyor
  • 36,596
  • 57
  • 175
  • 260
Leonhart231
  • 182
  • 2
  • 10

1 Answers1

3

The escape sequences are replaced at compile time, not at runtime by printf. "\n" is a string starting with a literal new-line character (it’s the only way to put a literal new-line character into a string).

The only part of the string printf interprets are conversion specification, which always start with a % sign, (and the 0-terminator, of course), every other character is printed literally. You don’t need to do anything further.

mafso
  • 5,433
  • 2
  • 19
  • 40
  • Ah, you're right, it is done at compile time. I'll cite the standard in an update to my question, since I found the actual text. Thank you! – Leonhart231 Aug 04 '14 at 23:07