best/proper way to declare constants ?

norm norm.rowtree at gmail.com
Fri Aug 6 05:53:38 UTC 2021


On Thursday, 5 August 2021 at 01:14:26 UTC, H. S. Teoh wrote:
> On Thu, Aug 05, 2021 at 12:47:06AM +0000, someone via 
> Digitalmars-d-learn wrote:
>> [...]
>
> 1) If the constant is a POD (int, float, etc.), use:
>
> 	enum myValue = ...;
>
> 2) If the constant is a string or some other array:
>
> 	static immutable string myString = "...";
> 	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) { ... }
> 	}
>
> Don't do this. Use static immutable for arrays and strings, use 
> enum only for PODs.
>
>
> T

The fact it requires this much explanation on how to declare a 
"best/proper" constant is not a great selling point for D. Sure, 
it is easy...once you know it and it reminds me of C++.

As a language D should strive to do better than this



More information about the Digitalmars-d-learn mailing list