best/proper way to declare constants ?

Steven Schveighoffer schveiguy at gmail.com
Thu Aug 5 02:43:09 UTC 2021


On 8/4/21 10:27 PM, someone wrote:
> On Thursday, 5 August 2021 at 02:06:13 UTC, Steven Schveighoffer wrote:
>> On 8/4/21 9:14 PM, H. S. Teoh wrote:
>>> 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.
>>
>> Just want to chime in and say this is NOT true for string literals. 
>> Only array literals.
> 
> OK. Not for arrays then ... but for string literals ? which one then ?
> 
> static immutable string fileName = "list.txt";
> 
> vs
> 
> enum fileName = "list.txt";

The main difference between enums and static immutable is that the 
latter has an address at runtime. You cannot take the address of an enum 
(which only exists at compile time). You can think of an enum to be a 
substitute for typing out that expression directly. For array literals, 
this means, do a new allocation.

However, a string literal is a special case of an array which does NOT 
allocate -- it puts the string data into the read-only segment, and the 
literal references that data, which is why string enums do not allocate 
when used.

So the answer is, depends on what you are going to do with the data. 
There are use cases for both. If you just want an alias to represent the 
literal, I'd say use enum, it should work fine.

Off the top of my head for strings:

1. A static immutable loses its "C string compatibility", whereas an 
enum does not.
2. A static immutable can be passed as an alias to a template, and the 
template mangle only involves the variable name, whereas passing an enum 
will use the string *contents* for the template mangle. This can be a 
huge difference for symbol sizes.
3. A static immutable can be used as an argument to a reference 
parameter, an enum cannot.
4. A static immutable will consume space in your executable even if 
never used, an enum will not.

-Steve


More information about the Digitalmars-d-learn mailing list