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

I read this one . The first answer by @Andrei T says that

A "large" object is never a constant expression in C, even if the object is declared const. Objects constructed using constants (of any type) are not constants in C 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 to do

static int j = N; /* ERROR */

      

you will get the same error: trying to initialize a static object with a volatile

I agree with his answer. I also tried a simple example like gcc 4.8.2 and 4.9.2 and 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 and works fine and gives the expected output. See the demo here . Also, in 13.12 IDE codeblocks (gcc 4.7.1) this program works fine. So is this a compiler error or a gcc extension? What combination of compiler options ideone

are used under the hood? So how and why does it compile to ideone

? What is the reason?

+3


source to share


2 answers


This is because ideon probably calls gcc

with an option -O

(optimization level 1). This applies to older versions too 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

      



Interestingly, with -pedantic

it works correctly again and a diagnostic message is present (tested only with 4.4.7,see Keith's comment sub>):

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

      

+2


source


This seems to be the specialty of gcc. Compiling with -std=c89

or -pedantic

reports an error.



Since this is a constraint violation in all C standards, without providing a diagnosis for this case, gcc without one of the options -std=c??

is an inappropriate compiler.

+3


source







All Articles