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.