www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Assign values to static array

reply Tommy <Tommy_member pathlink.com> writes:
Hello!

Why does the first version work, and the second doesn't?

// first version, works fine

import std.stream;
import std.cstream;

void main()
{
char[] foo;

foo = din.readString(2);
dout.writeLine(foo);
}

---

// second version, won't compile

import std.stream;
import std.cstream;

void main()
{
char[2] foo;

foo = din.readString(2);
dout.writeLine(foo);       // ERROR (see below)
}

---
DMD reports two error on the line marked with ERROR:
test.d(8): cannot change reference to static array 'foo'
test.d(8): cannot assign to static array foo
---

This seems like an unnecessary restriction to me: I create an array of two
chars. I assign two chars to that array. Looks completely logical to me.
Why doesn't it work though?
Even this compiles:
void main() {char[2] foo = "ab";}

Tommy
Sep 14 2005
parent reply "Regan Heath" <regan netwin.co.nz> writes:
On Wed, 14 Sep 2005 08:10:25 +0000 (UTC), Tommy  
<Tommy_member pathlink.com> wrote:
 Why does the first version work, and the second doesn't?

Because a "char[]" is a dynamic reference and a "char[2]" is a static reference. And the statement:
 foo = din.readString(2);

says "assign to 'foo' a reference to the result of din.readString(2)". This is illegal in the 2nd case because foo is a static reference, it's address cannot be changed, it cannot refer to anything other than what it already refers to, a 2 char long address in memory. It is important to note the difference between changing the referece/address and changing the values contained in an array, the line:
 foo[] = din.readString(2);

will work because this line says "copy the contents of the result of din.readString(2) into the chars at the address referenced by foo" Regan
Sep 14 2005
parent Tommy <Tommy_member pathlink.com> writes:
In article <opsw3hwupi23k2f5 nrage.netwin.co.nz>, Regan Heath says...

It is important to note the difference between changing the  
referece/address and changing the values contained in an array, the line:

 foo[] = din.readString(2);

will work because this line says "copy the contents of the result of din.readString(2) into the chars at the address referenced by foo"

Thanks heaps for your explanation, Regan. This last comment was particularly helpful. Tommy
Sep 14 2005