gpt4 book ai didi

c - 没有语法错误吗?应该 printf ("one" ", two and " "%s.\n", "three");是有效代码?

转载 作者:行者123 更新时间:2023-12-02 05:37:07 25 4
gpt4 key购买 nike

看看这段代码:

#include <stdio.h>

#define _ONE "one"
#define _TWO_AND ", two and "
int main()
{
const char THREE[6] = "three" ;
printf(_ONE _TWO_AND "%s.\n", THREE );
return 0;
}

printf 是有效的:

printf("one" ", two and " "%s.\n", "three" );

输出是:

one, two and three.

gcc 在编译此代码后既不给出错误也不给出警告消息。gcc 编译器应该以这种方式工作,还是一个错误?

最佳答案

这是标准行为,如果我们查看 C99 draft standard,相邻的字符串文字会连接在一起5.1.1.2 翻译阶段6 说:

Adjacent string literal tokens are concatenated

gcc 确实有许多非标准扩展,但是如果您使用 -pedantic 构建,那么 gcc 应该在它正在做某事时警告您非标准,您可以在文档部分阅读更多信息 Extensions to the C Language Family .

基本原理包含在 Rationale for International Standard—Programming Languages—C 中它在 6.4.5 String literals 部分说:

A string can be continued across multiple lines by using the backslash–newline line continuation, but this requires that the continuation of the string start in the first position of the next line. To permit more flexible layout, and to solve some preprocessing problems (see §6.10.3), the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together, with no null character in the middle, to make one combined string literal. This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism and thereby destroying the indentation scheme of the program. An explicit concatenation operator was not introduced because the concatenation is a lexical construct rather than a run-time operation.

关于c - 没有语法错误吗?应该 printf ("one" ", two and " "%s.\n", "three");是有效代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20548200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com