enum str = "abc"; vs string str = "abc";

Johannes Loher johannes.loher at fg4f.de
Wed Jan 16 19:14:34 UTC 2019


On Wednesday, 16 January 2019 at 19:06:18 UTC, Johannes Loher 
wrote:
> On Wednesday, 16 January 2019 at 18:50:51 UTC, H. S. Teoh wrote:
>> Also, you may have no choice but to use an enum if `str` is 
>> referenced by compile-time code, since static globals would 
>> not be readable at compile-time.
>
> They are, if they are declared immutable (which is no problem 
> if using enum would also be ok). The following program outputs 
> "0" during compilation:
>
> ```
> static immutable i = 0;
>
> static if (i == 0)
> {
>     pragma(msg, i);
> }
>
> void main()
> {
>
> }
> ```

Actually in this case, it can also simply be `immutable i = 0;`, 
the `static` keyword doesn't do anything in this case. This also 
works and also prints "0" during compilation:
```
void main()
{
     static immutable i = 0;

     static if (i == 0)
     {
         pragma(msg, i);
     }
}
```

The argument for using `static immutable` (or `immutable` at 
module level) is that unlike enum, it will only ever use one 
instance. It will not allocate several times. As was mentioned 
before, this is also true for `enum` when used with strings, but 
strings are a special case. For other array types (and 
associative array types), a new instance is allocated whenever 
the `enum` is used.


More information about the Digitalmars-d mailing list