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

前端 未结 2 1398
栀梦
栀梦 2021-01-06 07:48

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 a

相关标签:
2条回答
  • 2021-01-06 08:19

    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
    

    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
    
    0 讨论(0)
  • 2021-01-06 08:38

    This seems to be a gcc speciality. Compiling with -std=c89 or -pedantic reports the error.

    Since in all C standards this is a constraint violation, not giving a diagnostic for that case makes gcc without one of the -std=c?? options a non-conforming compiler.

    0 讨论(0)
提交回复
热议问题