real simple manifest constant question probably regret asking...

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 15 20:38:35 PDT 2017


WhatMeForget wrote:

> One of my D books says: "an enum declared without any braces is called a 
> manifest constant." The example shows,
>
> enum string author = "Mike Parker";
>
> Is this equivalent to
> const string author = "Mike Parker";
> or
> immutable string author = "Mike Parker";
>
> I guess what I'm asking is does enum give you some advantages over say 
> non-enum constants?
>
> Thanks.

"enum constants" are so-called "inline constants". i'll try to explain it.

imagine that you have a constant:

	int[2] carr = [ 42, 69 ];

this array will be placed in read-only data segment, and each time you 
refer to it, the same array will be used. i.e.

	assert(carr.ptr is carr.ptr);

will pass.

now let's try

	enum int[2] carr = [ 42, 69 ];

this time,

	assert(carr.ptr is carr.ptr);

will fail.

why? 'cause when you are using "enum constant", it will be created 
in-place. i.e. in the second case you'll get *two* arrays with identical 
content.


wether you want that effect or not is completely up to you. usually, it is 
better to declare numeric constants as enums (so they won't take any 
storage at all), and array constants as `immutable`s.

as for strings, it depends of your system, compiler and linker. usually, 
linkers "deduplicating" strings (i.e. merging identical strings into one), 
but if your string is heavily used, it may still be better to declare it as 
non-enum.


More information about the Digitalmars-d-learn mailing list