digitalmars.D.learn - Assign values to static array
- Tommy (32/32) Sep 14 2005 Hello!
- Regan Heath (13/16) Sep 14 2005 Because a "char[]" is a dynamic reference and a "char[2]" is a static
- Tommy (4/9) Sep 14 2005 Thanks heaps for your explanation, Regan. This last comment was
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
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
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:Thanks heaps for your explanation, Regan. This last comment was particularly helpful. Tommyfoo[] = 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"
Sep 14 2005








Tommy <Tommy_member pathlink.com>