www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Static initialization of pointers

The D language specification under "Global and static 
initializers" [1], says the following:

 The Initializer for a global or static variable must be
 evaluatable at compile time. Whether some pointers can be
 initialized with the addresses of other functions or data
 is implementation defined. Runtime initialization can be
 done with static constructors.
What is the rationale of making this implementation defined? What's the range of possible behaviors? Are there any circumstances in which a pointer can't be initialized with an address of a function or data? If so, couldn't a subset of cases have an explicitly defined, portable behavior? As far as I've tested this, DMD, GDC and LDC can handle static initialization of pointers to functions or data (except that LDC fails if function pointer(s) are obtained via __traits(getUnitTests, module_name)), even across separately compiled modules, which is consistent with a similar feature of C and C++. IIUC, the C standard always allows such initialization. In 6.6 Constant expressions, N1570 [2] says:
 7 More latitude is permitted for constant expressions
 in initializers. Such a constant expression shall be,
 or evaluate to, one of the following:
 — an arithmetic constant expression,
 — a null pointer constant,
 — an address constant, or
 — an address constant for a complete object type
   plus or minus an integer constant expression.
 9 An address constant is a null pointer, a pointer to an
 lvalue designating an object of static storage duration,
 or a pointer to a function designator; it shall be created
 explicitly using the unary & operator or an integer constant
 cast to pointer type, or implicitly by the use of an
 expression of array or function type. The array-subscript []
 and member-access . and -> operators, the address & and
 indirection * unary operators, and pointer casts may be used
 in the creation of an address constant, but the value of an
 object shall not be accessed by use of these operators.
[1] https://dlang.org/spec/declaration.html#global_static_init [2] http://iso-9899.info/n1570.html
Jul 27