Clang and gcc different behavior with compound literal

A connection has recently appeared with a mixed literal, and, as I understand it, it is more correct to use it. Fortunately, it works with both gcc and clang on ubuntu.

int main() {
  int *p = (int []) {1, 2};
  return 0;
}

However, I notice another way to use the composite literal shown below. It's a bit strange; it's just an array initializer. The following code is compiled using a clang, but not with the gcc, array initialized from non-constant array expression.

int main() {
  int p[] = (int []) {1, 2};
  return 0;
}

Is it intentional or what?

ENV:

  • gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
  • Ubuntu clang version 3.5-1ubuntu1 (trunk) (based on LLVM 3.5)

CMD:

  • gcc test.c
  • clang test.c
+4
source share
2 answers

: ,

, , int p[] = (int []) {1, 2};, Clang. GCC , C99 (C99 standard ).

, Clang , . , " GNU":

~ $ clang -std=c99 -pedantic t.c
t.c:2:7: warning: initialization of an array of type 'int []' from a compound
      literal of type 'int [2]' is a GNU extension
      [-Wgnu-compound-literal-initializer]
  int p[] = (int []) {1, 2};
      ^     ~~~~~~~~~~~~~~~
1 warning generated.
~ $ clang -v
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

int p[] = (int []) {1, 2}; - . , 6.7:

6.7

1

declaration:
    declaration-specifiers init-declarator-listopt ;

declaration-specifiers:
    storage-class-specifier declaration-specifiersopt
    type-specifier declaration-specifiersopt
    type-qualifier declaration-specifiersopt
    function-specifier declaration-specifiersopt

init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator

init-declarator:
    declarator
    declarator = initializer

, 6.7.8:

6.7.8

1

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }

...

12 .

...

16 .

6.7.8: 16 . , C99, .

+6

C99 ++.

++ , . ++, , .

@cremno .

0

Source: https://habr.com/ru/post/1569639/


All Articles