Newbie style question about string constants
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Feb 25 00:34:45 UTC 2025
On Monday, February 24, 2025 9:07:07 AM MST Ian via Digitalmars-d-learn wrote:
> Hello,
>
> What's the recommended D way to declare a string constant? Say,
> for example, for a path used inside a class constructor? I've
> seen const string, immutable, enum etc...
>
> Is this the place for these kinds of questions? Is there a D
> stack overflow?
For strings, the way that you normally do constants is with enum, e.g
enum foo = "dlang";
An enum like this is called a manifest constant. And you use manifest
constants for most constants in D, with the caveat that for anything other
than a string which involves an allocation, you probably don't want to use
an enum. That's because enums are not variables, and their values are
essentially copy-pasted wherever they're used. So, if you do something like
enum foo = [1, 2, 3];
everywhere that you use foo, it'll be the same as if you used [1, 2, 3]
directly. And because [1, 2, 3] allocates a new array, that means that each
use of the enum allocates a new array. In such a situation, using a static
variable would be better, e.g.
static immutable foo = [1, 2, 3];
That does create a variable, so wherever you use foo, the array is sliced
(so you get two arrays referring to the same piece of memory) rather than
resulting in a new allocation.
However, for strings, this is not an issue. This is because the compiler
stores string literals directly in the program (in the ROM section of the
binary on some OSes) and then slices that memory rather than allocating a
new string every time you use the string literal. So, if you used "dlang"
all over your program, you wouldn't get any allocations (unlike with
[1, 2, 3]). And using an enum that's a string has the same result. So,
typically, enums are used for constants which are strings - the same with
int and other types which involve no allocations - whereas for other types
of arrays, an immutable static variable is generally better.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list