www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - String Literals (D 2.0)

reply Xinok <xnknet gmail.com> writes:
I find this a bit annoying:
char[] str = "Test String";
Error: cannot implicitly convert expression ("Test String") of type 
invariant char[11] to char[]

Yet if you write:
int[] str = [10, 20, 30];
It gives no error.

I think the default behavior for string literals should be the same as 
array literals. And if the user does want a const or invariant string:
const str = "Test String";
invariant str = "Test String";
Jun 18 2007
parent reply "Vladimir Panteleev" <thecybershadow gmail.com> writes:
On Tue, 19 Jun 2007 00:36:10 +0300, Xinok <xnknet gmail.com> wrote:

 I find this a bit annoying:
 char[] str =3D "Test String";
 Error: cannot implicitly convert expression ("Test String") of type
 invariant char[11] to char[]

String literals will be placed in "read-only" memory while compiling. Wr= iting to this area should generate an exception, although it doesn't on = Windows. If you'd like to change the string's contents after initializin= g it, consider writing char[] str =3D "Test String".dup;
 Yet if you write:
 int[] str =3D [10, 20, 30];
 It gives no error.

I'm not sure whether integer literals are also placed in the same data s= egment for read-only memory. If it is, then it's a bug - all array liter= als should be immutable.
 I think the default behavior for string literals should be the same as=

 array literals. And if the user does want a const or invariant string:=

 const str =3D "Test String";
 invariant str =3D "Test String";

My opinion is just that there should be a simple (castless, .dup-less) w= ay to put string and array literals into the initialized data segment - = that is, where you give it an initial value but can still write to it. -- = Best regards, Vladimir mailto:thecybershadow gmail.com
Jun 18 2007
parent Xinok <xnknet gmail.com> writes:
Vladimir Panteleev wrote:
 Yet if you write:
 int[] str = [10, 20, 30];
 It gives no error.

I'm not sure whether integer literals are also placed in the same data segment for read-only memory. If it is, then it's a bug - all array literals should be immutable.

I wrote a simple test to figure out what exactly the compiler does with array literals: void test1(int count = 3){ if(count > 0) test1(count-1); int[] arr = [10, 20, 30]; writefln(&arr[0]); } void test2(int count = 3){ if(count > 0) test2(count-1); invariant int[] arr = [10, 20, 30]; writefln(&arr[0]); } void main(){ test1(); test2(); } The results: 880FE0 880FD0 880FC0 880FB0 415080 415080 415080 415080 For mutable types, the array literal is dup'd. For invariant types, the array literal is referenced. I prefer it this way, and I hope the same will be done for string literals.
Jun 19 2007