Possible Duplicate:
Definition of global variables using a non constant initializer
I have this code:
#include <stdio.h>
#include <stdlib.h>
int foo (int num, int i)
{
static int* array = malloc(sizeof(int)); // ERROR HERE!!!
printf("%d", array[i]);
return 0;
}
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 2; i++) {
foo(i, i);
}
return 0;
}
I save the code as a c source file, I can’t work? the error prompt:
gcc -O2 -Wall test.c -lm -o test
test.c:4:1: error: initializer element is not constant
Compilation exited abnormally with code 1 at Sat Jan 05 21:33:56
However, I save it as a C++ source file, It works OK. Why? is there anybody can explain it to me?
C and C++ standards treat initialization of objects with
staticstorage duration differently. C++ allows both static initialization (i.e. initialization with a constant) and dynamic initialization (i.e. initialization with non-constant expression), while C allows only static initialization – i.e. with constant expressions.The relevant portion of the C++ standard is 6.7.4:
C++ need additional “bookkeeping” in order to run the dynamic portion of your initializer (i.e. the call of
malloc) only once. There is no similar “dynamic” provision in the C standard:In the absence of concurrency, you can rewrite the code for use with C like this:
Now your code is responsible for the “bookkeeping”: it checks
arrayforNULLbefore performing the allocation.