我写了一个简单的 C 程序来测试 _Generic 关键字的可用性。
int main() {
int _Generic;
}
我在 Ubuntu 上使用 gcc-5.3.1 和 clang-3.8.0 编译器运行程序。
很明显,这个程序在最新的 c11 标准中编译时产生了错误。
但是,当使用 -std=c90 和 -std=c99 标志编译时,它也会生成错误。然而,_Generic 关键字仅在 c11 标准中引入。
是不是 -std= 标志的行为不同?有没有办法测试纯 c90 和 c99 标准?
编辑:
我确实使用其他标识符运行了相同的程序,这些标识符不是按照 c11 标准的关键字。喜欢:
int _Hello;
int _Gener;
他们编译成功,没有任何错误或警告。 这可能是因为 7.1.3,它说
If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined
正如@Art 和@Lundin 所说。
最佳答案
因为不允许使用以下划线开头后跟大写字母的标识符。 7.1.3:
All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
这条规则从 C90 开始就有了,并不是什么新鲜事。
测试标准版本的更可靠方法是使用为此目的定义的标准宏:
#ifndef __STDC__
#error Not a standard C compiler.
#endif
#ifdef __STD_VERSION__
#if (__STDC_VERSION__ == 199409L)
/* C95 */
#elif (__STDC_VERSION__ == 199901L)
/* C99 */
#elif (__STDC_VERSION__ == 201112L)
/* C11 */
#else
/* Cxx, unknown future standard */
#endif
#else /* __STDC__ defined but not __STD_VERSION__ */
/* C90 */
#endif
关于c - 为什么在 c99 或 c90 模式中支持 _Generic 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44590043/