Tuesday, 15 February 2011

Does C allows non-const expressions in array initializer list? -



Does C allows non-const expressions in array initializer list? -

in next code a array initialized s "seed" variable, not constant look (as it's evaluated "run-time"):

#include <stdio.h> int main(void) { int s = 1, i; int a[] = {s, s + 2, s + 4, s + 6, s + 8}; (i = 0; < (int) (sizeof / sizeof a[0]); i++) printf("%d ", a[i]); /* prints: 1 3 5 7 9 */ putchar('\n'); homecoming 0; }

it compiles in gcc -wall -wextra no warnings. adding -pedantic provokes:

check.c: in function ‘main’: check.c:8: warning: initializer element not computable @ load time check.c:8: warning: initializer element not computable @ load time check.c:8: warning: initializer element not computable @ load time check.c:8: warning: initializer element not computable @ load time check.c:8: warning: initializer element not computable @ load time

does c require constant look initializer elements ?

this valid in c99 not valid in c89 (emphasize mine):

(c89, 6.5.7) "all look in initializer object has static storage duration or in initializer list object has aggregate or union type shall constant expressions"

but

(c99, 6.7.8p4) "all expressions in initializer object has static storage duration shall constant expressions or string literals."

by default, gcc compiles -std=gnu89 c89 + gnu extensions.

c

No comments:

Post a Comment