Domanda

Is this a bug in Clang? The following code:

#include <stdio.h>

int main(void)
{
    int foo = 42;
    int bar[1] = { foo };
    printf("%d\n", bar[0]);
    return 0;
}

Compiles fine using:

clang -Wall -Wextra -Werror -pedantic -pedantic-errors -std=c89 -o foo foo.c

I don't think it should compile, since the initializer list of bar[] contains an expression, foo, which is not a compile-time constant. Indeed, if I use gcc instead of clang, I get the expected results:

$ gcc -Wall -Wextra -Werror -pedantic -pedantic-errors -std=c89 -o foo foo.c
foo.c: In function ‘main’:
foo.c:6: error: initializer element is not computable at load time

This question and its accepted answer, along with extracts of this C89 description suggest that GCC is right and Clang is wrong:

The expressions in initializer for static object, or for aggregate or union, must be constant expressions.

My version of clang is:

$ clang -v
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin11.4.2

One thing I noticed is that the latest revision of clang that is present on opensource.apple.com, i. e. clang 425.0.24, is only 4 subminor revisions older than my clang, and it does have unit tests for array initializers. However, unless I'm missing something, there's no test for the initialization of block-scope automatic arrays with non-const expressions (only block-scope static arrays and global arrays are tested). Here's the test file I found.

So, what's the deal?

È stato utile?

Soluzione

This looks like a bug in the older version of clang since version 3.5 gives me the following warning for this code:

warning: initializer for aggregate is not a compile-time constant [-Wc99-extensions]
int bar[1] = { foo };
             ^~~~~~~

and an error with your compile options (see it live).

Lacking a public C89 draft, I found gcc has a section on Non-Constant Initializers which says:

As in standard C++ and ISO C99, the elements of an aggregate initializer for an automatic variable are not required to be constant expressions in GNU C.

which confirms that they used to be required to be constant expressions pre C99.

As tab informs us, the relevant quote from the C89 standard is from sectioon 3.5.7 and says:

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top