[英]Why is putchar printing formatted output?
I've wanted to learn more about the C standard library, so I decided to implement printf
using only the putchar
function. 我想了解有关C标准库的更多信息,所以我决定仅使用putchar
函数来实现printf
。 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. 我要做的就是编写一个循环,以打印格式字符串的逐字记录副本,然后我意识到所有转义序列( \\n
, \\t
等)都已被解析并“正确地”输出了。
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\\t1\\n0\\n
,但是我却得到了:
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. 我首先想到的是,我使用的编译器(gcc)试图通过预先分析格式字符串来提供帮助,但这似乎很奇怪,因为这会导致很多问题,因为它将破坏任何char
数组。 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. 编辑:如mafso在其回答中所述,替换是在编译时完成的,并且是标准的。 Section 5.1.1.2.1.5 of the standard has the actual text. 标准的5.1.1.2.1.5节有实际文本。
The escape sequences are replaced at compile time, not at runtime by printf
. 转义序列在编译时而不是在运行时由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). "\\n"
是一个以文字换行符开头的字符串(这是将文字换行符放入字符串中的唯一方法)。
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. 字符串printf
解释的唯一部分是转换规范,该规范始终以%
符号开头(当然还有0终止符),所有其他字符都按字面意义打印。 You don't need to do anything further. 您不需要做任何其他事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.