Why it is allowed to initialize static variable with non const here?

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

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

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);
}

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?


Source: gcc

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.