解释一下C代码片段:预处理器+打印=?

发布于 2024-09-17 12:37:27 字数 190 浏览 3 评论 0原文

此代码片段的输出是 %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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

趁年轻赶紧闹 2024-09-24 12:37:27

您究竟希望我们解释什么?替换宏并获取

printf("%s is a string", "%s is a string");

剩下的就是 printf 的预期正常日常行为。

PS #define scanf ...???

What exactly do you want us to explain? Subsititute the macro and get

printf("%s is a string", "%s is a string");

The rest is the expected normal everyday behavior of printf.

P.S. #define scanf ...???

情深如许 2024-09-24 12:37:27

预处理器进行盲替换以给出:

printf("%s is a string","%s is a string");

第一个参数中的 %s 是字符串的格式说明符,并被第二个参数替换。第二个参数中的 %s 没有什么特别的。

The preprocessor does a blind substitution to give:

printf("%s is a string","%s is a string");

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.

殊姿 2024-09-24 12:37:27

这是一些相当奇怪的代码,但输出将是“%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.

终陌 2024-09-24 12:37:27

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.

无尽的现实 2024-09-24 12:37:27

要理解这段代码,请一一运行以下语句:-

printf("%s is a string","StRiNG");
printf("%s %s is a string","StRiNG");
printf("%s is a string","StRiNG","Hey");

to understand this code,run the following statements one by one:-

printf("%s is a string","StRiNG");
printf("%s %s is a string","StRiNG");
printf("%s is a string","StRiNG","Hey");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文