best/proper way to declare constants ?

someone someone at somewhere.com
Thu Aug 5 01:39:42 UTC 2021


On Thursday, 5 August 2021 at 01:14:26 UTC, H. S. Teoh wrote:
> 1) If the constant is a POD (int, float, etc.), use:
>
> 	enum myValue = ...;

crystal-clear.

> 2) If the constant is a string or some other array:
>
> 	static immutable string myString = "...";

crystal-clear.

> 2) If the constant is a string or some other array:
>
> 	static immutable Data[] myData = [ ... ];
>
> Unless you have a specific reason to, avoid using `enum` with 
> string and array literals, because they will trigger a memory 
> allocation *at every single reference to them*, which is 
> probably not what you want.
>
> 	enum myArray = [ 1, 2, 3 ];
> 	...
> 	int[] data = myArray;	// allocates a new array
> 	int[] data2 = myArray;	// allocates another array
>
> 	// they are separate arrays with the same contents
> 	assert(data !is data2);
> 	assert(data == data2);
>
> 	// allocates a temporary array, does the comparison, then
> 	// discards the temporary
> 	if (data == myArray) ...
>
> 	foreach (i; 0 .. 10) {
> 		int[] input = getUserInput(...);
>
> 		// allocates a new array at every single loop iteration
> 		if (input == myArray) { ... }
> 	}

What happens in the following case ?

public immutable enum gudtLocations = [
    r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),
    r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
    r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),
    r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
    r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
    ];

This is something that I also need at compilation time.

Throwing away the enum and recoding as following:

static immutable structureLocation[stringUTF32] gudtLocations = [
    r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),
    r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
    r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),
    r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
    r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
    ];

gives me:

Error: non-constant expression `["BUE"d:structureLocation(true, 
"arg"d, null, "Buenos Aires"d, "ART"d), 
"GRU"d:structureLocation(true, "bra"d, null, "S\xe3o Paulo"d, 
"BRT"d), "HHN"d:structureLocation(true, "deu"d, null, "Frankfurt 
am Main"d, "CET"d), "LHR"d:structureLocation(true, "gbr"d, null, 
"London"d, "UTC"d), "NYC"d:structureLocation(true, "usa"d, null, 
"New York"d, "EST"d)]`

> Don't do this. Use static immutable for arrays and strings, use 
> enum only for PODs.

crystal-clear.


More information about the Digitalmars-d-learn mailing list