C and C ++ standards handle object initialization with static storage duration in different ways. C ++ allows both static initialization (i.e., initialization with a constant) and dynamic initialization (i.e., initialization with a mutable expression), while C only allows static initialization, i.e. With constant expressions.
The relevant part of the C ++ standard is 6.7.4:
Zero initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before any other initialization. A local object of type POD (3.9) with a static storage duration, initialized by constant expressions, is initialized before its block is entered first. [...] Otherwise, such an object is initialized, the first time control passes through its declaration; such an object is considered initialized after completion of its initialization. (highlighted by me)
C ++ requires an additional โaccountโ to start the dynamic part of your initializer (ie calling malloc ) only once. There is no such โdynamicโ provision in the C standard:
Before starting the program, all objects with static storage must be initialized (set to their initial values). All expressions in the initializer for an object with a duration of static storage must be constant expressions or string literals.
In the absence of concurrency, you can rewrite the code for use with C as follows:
int foo (int num, int i) { static int* array = NULL; if (!array) array = malloc(sizeof(int));
Now your code is responsible for accounting: it checks the array for NULL before performing the allocation.
source share