string literals

Jonathan M Davis jmdavisProg at gmx.com
Fri May 31 08:35:35 PDT 2013


On Friday, May 31, 2013 16:20:44 Jack Applegame wrote:
> What's the reason that the string literal is a dynamic array, not
> a static?

Would you really want to end up with a copy of a string literal every time you 
used it? The fact that they're immutable and can be passed around without ever 
being copied is a definite efficiency boost for handling string literals (and a 
lot of string handling involves string literals). Making them static arrays 
wouldn't buy us anything and would cost us a lot.

> So sometimes it is not possible to get string length compile time:
> 
> void foo(T: E[N], E, size_t N)(auto ref T data) {
> pragma(msg, "static");
> pragma(msg, data.length);
> }
> void foo(T: E[], E)(auto ref T data) {
> pragma(msg, "dynamic");
> pragma(msg, data.length);
> // Error: variable data
> // cannot be read at compile time
> }
> ...
> foo("test");

You can't get the length there because data is not known at compile time. The 
variable must be known at compile time for it to work with pragma. The fact 
that it's a string is irrelevant, and making it a static array woludn't help 
any. If data were a template argument, it would work, but it's a funciton 
argument, so it won't.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list