为什么在这里允许使用非const初始化静态变量? [英] Why it is allowed to initialize static variable with non const here?

查看:84
本文介绍了为什么在这里允许使用非const初始化静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读。 @Andrei T的第一个答案是

I was reading this. The first answer by @Andrei T says that


即使 $ b $存在,大对象也不是C中的常量表达式。 b对象声明为const。 const限定的对象(任何类型)都是
,而不是C语言术语中的常量。不管
的类型如何,都不能在具有静态存储持续时间的对象的
初始化程序中使用它们。

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.

例如,这不是常量

const int N = 5; /* `N` is not a constant in C */

以上N将是C中的常数C ++,但在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及以上它会产生我所期望的编译器错误:

I agree with his answer. I also tried a simple example like following on gcc 4.8.2 & 4.9.2 & it gives compiler errors as I expected:

#include <stdio.h>
int main(void)
{
    const int a=5;
    static int b=a;
    printf("%d",b);
}

但是当我在 ideone.com上尝试过它会编译&运行良好,并给出了预期的结果。请在此处中查看现场演示。另外,在代码块13.12 IDE(gcc 4.7.1)上,该程序运行良好。那么,它是编译器错误还是gcc扩展? ideone 使用的编译器选项是什么?因此,如何为什么在 ideone 中编译?是什么原因?

But When I tried it on ideone.com it compiles & runs fine and gives expected outcome. See live demo here. Also, on codeblocks 13.12 IDE (gcc 4.7.1) this program runs fine. So, Is it compiler bug or gcc extension? What combination of compiler options ideone uses under the hood? So, how & why it compiles in ideone? What is the reason?

推荐答案

这是因为ideone 可能调用了 gcc -O 选项(优化级别1)。甚至对于 gcc 的旧版本(我的是4.4.7)也是如此:

It's because the ideone likely invokes gcc with -O option (optimization level 1). This is the case even for older versions of gcc (mine is 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, 请参阅Keith的评论 ):

What's interesting here is that with -pedantic it is working properly again and required diagnostic message is present (tested only with 4.4.7, see Keith's comment):

gcc -ansi -pedantic -O main.c 
main.c: In function ‘main’:
main.c:6: error: initializer element is not constant
$ echo $?
1

这篇关于为什么在这里允许使用非const初始化静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆