解释一下C代码片段:预处理器+打印=?
此代码片段的输出是 %s is a string is a string
。请解释一下。
#include <stdio.h>
#define scanf "%s is a string"
int main()
{
printf(scanf, scanf);
}
The output for this code snippet is %s is a string is a string
. Please explain.
#include <stdio.h>
#define scanf "%s is a string"
int main()
{
printf(scanf, scanf);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您究竟希望我们解释什么?替换宏并获取
剩下的就是
printf
的预期正常日常行为。PS
#define scanf ...
???What exactly do you want us to explain? Subsititute the macro and get
The rest is the expected normal everyday behavior of
printf
.P.S.
#define scanf ...
???预处理器进行盲替换以给出:
第一个参数中的
%s
是字符串的格式说明符,并被第二个参数替换。第二个参数中的%s
没有什么特别的。The preprocessor does a blind substitution to give:
The
%s
in the first argument is the format specifier for a string and is replaced with the 2nd argument. There is nothing special about the%s
in the 2nd argument.这是一些相当奇怪的代码,但输出将是“%s 是一个字符串是一个字符串”,因为在这两种情况下 scanf 都扩展为“%s 是一个字符串”,然后 printf 将其替换为 %s。
This is some rather bizarre code, but the output would be "%s is a string is a string" because scanf is expanded to "%s is a string" in both cases and then printf substitutes that in for the %s.
printf("%s 是一个字符串","%s 是一个字符串");
我想令人困惑的是 printf 将如何处理第二个 %s。
要澄清这一点,printf 不是递归函数。如果您正在打印字符串并且该字符串具有任何格式标识符,则它不会被视为格式标识符。它被视为普通字符串。因此,在这种情况下,第二个“%s 是字符串”只是一个普通字符串。该字符串中的 %s 不是格式标识符。
如果你有类似 printf("%s %s 是一个字符串", "%s %s 是一个字符串"); 的东西
然后,是的,您将收到运行时错误,指出 printf 缺少某些参数。
printf("%s is a string","%s is a string");
I guess the confusion is what the printf will do with the second %s.
To clear this, printf is not a recursive function. If you are printing a string and that string has any format-identifier it is not considered as format identifier. It is considered as plain string. So in this case the second "%s is a string" is just a plain string. %s in this string is not format-identifier.
If you had something like printf("%s %s is a string", "%s %s is a string");
Then yes you will get runtime error saying that printf is missing some argument.
要理解这段代码,请一一运行以下语句:-
to understand this code,run the following statements one by one:-