June 05, 2012
(Influenced by a discussion in the main D newsgroup.)

The assert check in the following program passes, indicating that 'a' is not 'a'! :p

enum a = [ 1, 2 ];

void main()
{
    assert(a.ptr != a.ptr);
}

Apparently this is due to enum arrays being created every time they are used. What is the rationale for this? Is this a limitation of the language, dmd, linker?

Surprisingly, it is not surprising ;) when it is a character array:

enum a = "hello";

void main()
{
    assert(a.ptr == a.ptr);  // <-- this time equals
}

I remember reading similar issues with associative arrays. Is that still the case? What are the rules for using enum vs. immutable? Should we use 'enum' for value types but 'immutable' for reference types? (Which is clearly not a good guideline, given the "hello" example above).

Thank you,
Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
June 05, 2012
On Monday, June 04, 2012 18:12:57 Ali Çehreli wrote:
> (Influenced by a discussion in the main D newsgroup.)
> 
> The assert check in the following program passes, indicating that 'a' is not 'a'! :p
> 
> enum a = [ 1, 2 ];
> 
> void main()
> {
> assert(a.ptr != a.ptr);
> }
> 
> Apparently this is due to enum arrays being created every time they are used. What is the rationale for this? Is this a limitation of the language, dmd, linker?
> 
> Surprisingly, it is not surprising ;) when it is a character array:
> 
> enum a = "hello";
> 
> void main()
> {
> assert(a.ptr == a.ptr); // <-- this time equals
> }
> 
> I remember reading similar issues with associative arrays. Is that still the case? What are the rules for using enum vs. immutable? Should we use 'enum' for value types but 'immutable' for reference types? (Which is clearly not a good guideline, given the "hello" example above).

This is how manifest constants work. They don't actually exist. They're copy- pasted everywhere that they're used. If you want an actual variable rather than a manifest constant, then you declare a variable (and make it const or immutable if you want a constant). The side effect of this for something like an array is that you end up with a new array everywhere that it's used rather than a slice of the original (since there is no original), which can effect a negative effect on performance if you aren't expecting all of those additional heap allocations.

- Jonathan M Davis