为什么这里允许用非 const 初始化静态变量?
Why it is allowed to initialize static variable with non const here?
我正在阅读 this。 @Andrei T 的第一个回答是
A "large" object is never a constant expression in C, even if the
object is declared as const. Const-qualified objects (of any type) are
not constants in C language terminology. They cannot be used in
initializers of objects with static storage duration, regardless of
their type.
For example, this is NOT a constant
const int N = 5; /* `N` is not a constant in C */
The above N would be a constant in C++, but it is not a constant in C.
So, if you try doing
static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object
with a non-constant
我同意他的回答。我还尝试了一个简单的例子,比如下面的 gcc 4.8.2 & 4.9.2 & 它给出了我预期的编译器错误:
#include <stdio.h>
int main(void)
{
const int a=5;
static int b=a;
printf("%d",b);
}
但是当我在 ideone.com
上尝试它时,它编译并运行良好并给出了预期的结果。查看现场演示 here。此外,在代码块 13.12 IDE (gcc 4.7.1) 上,该程序运行良好。那么,它是编译器错误还是 gcc 扩展?编译器选项 ideone
背后使用的是什么组合?那么,它如何以及为何在 ideone
中编译?这是什么原因?
这似乎是 gcc 的特色。用-std=c89
或-pedantic
编译报错。
因为在所有 C 标准中,这都是违反约束的,因此不对这种情况进行诊断会使没有 -std=c??
选项之一的 gcc 成为不合格的编译器。
这是因为 ideone 可能 调用 gcc
和 -O
选项(优化级别 1)。即使是 gcc
的旧版本也是如此(我的是 4.4.7):
$ gcc -ansi main.c
main.c: In function ‘main’:
main.c:6: error: initializer element is not constant
$ gcc -ansi -O main.c
$ echo $?
0
这里有趣的是 -pedantic
它再次正常工作并且存在所需的诊断消息(仅使用 4.4.7 测试, ):
gcc -ansi -pedantic -O main.c
main.c: In function ‘main’:
main.c:6: error: initializer element is not constant
$ echo $?
1
我正在阅读 this。 @Andrei T 的第一个回答是
A "large" object is never a constant expression in C, even if the object is declared as const. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.
For example, this is NOT a constant
const int N = 5; /* `N` is not a constant in C */
The above N would be a constant in C++, but it is not a constant in C. So, if you try doing
static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant
我同意他的回答。我还尝试了一个简单的例子,比如下面的 gcc 4.8.2 & 4.9.2 & 它给出了我预期的编译器错误:
#include <stdio.h>
int main(void)
{
const int a=5;
static int b=a;
printf("%d",b);
}
但是当我在 ideone.com
上尝试它时,它编译并运行良好并给出了预期的结果。查看现场演示 here。此外,在代码块 13.12 IDE (gcc 4.7.1) 上,该程序运行良好。那么,它是编译器错误还是 gcc 扩展?编译器选项 ideone
背后使用的是什么组合?那么,它如何以及为何在 ideone
中编译?这是什么原因?
这似乎是 gcc 的特色。用-std=c89
或-pedantic
编译报错。
因为在所有 C 标准中,这都是违反约束的,因此不对这种情况进行诊断会使没有 -std=c??
选项之一的 gcc 成为不合格的编译器。
这是因为 ideone 可能 调用 gcc
和 -O
选项(优化级别 1)。即使是 gcc
的旧版本也是如此(我的是 4.4.7):
$ gcc -ansi main.c
main.c: In function ‘main’:
main.c:6: error: initializer element is not constant
$ gcc -ansi -O main.c
$ echo $?
0
这里有趣的是 -pedantic
它再次正常工作并且存在所需的诊断消息(仅使用 4.4.7 测试,
gcc -ansi -pedantic -O main.c
main.c: In function ‘main’:
main.c:6: error: initializer element is not constant
$ echo $?
1