Stop using the enum as a manifest constant.

Jack Applegame japplegame at gmail.com
Sun Jun 6 18:34:23 UTC 2021


On Sunday, 6 June 2021 at 15:05:47 UTC, Mathias LANG wrote:
> ```D
> import std.stdio;
> int[] foo() @safe { return [42, 42, 42]; }
> enum WAT = foo();
> void main() @safe {
>     bar();
> }
> void bar(int[] data = WAT) @safe
> {
>     data[0] = 84;
>     writeln(data);
>     writeln(WAT);
> }
> ```
>
> The above works as expected (at least, as *I* would expect). 
> However, change the type to `char[]` and it SEGV. That's 
> probably because string literals are special and the compiler 
> makes some (bad) assumptions.

It's definetly a code smell.
Here are much better solutions:
```d
char[] foo() pure { return "hello".dup; }
immutable DEFAULT = foo();

void bar(char[] data = DEFAULT.dup) {
     data[0] = '1';
     // DEFAULT[0] = '2'; Error: cannot modify `immutable` 
expression `DEFAULT[0]`
     writeln(data);
     writeln(DEFAULT);
}
```
It uses explicit copying instead of the undocumented "feature" of 
the enum.

Or just use function directly
```d
char[] DEFAULT() pure { return "hello".dup; }

void bar(char[] data = DEFAULT) {
     data[0] = '1';
     DEFAULT[0] = '2';
     writeln(data);
     writeln(DEFAULT);
}

// works too
void baz(string data = DEFAULT) {}
```


More information about the Digitalmars-d mailing list