digitalmars.D.learn - How does array assignment for different sized types work?
- estew (15/15) Jan 30 2013 void main() {
- Jacob Carlborg (6/13) Jan 30 2013 There are dynamic arrays and static arrays. Dynamic arrays are reference...
- estew (1/5) Jan 31 2013 Got it. Thanks very much for the help.
- Timon Gehr (17/22) Jan 31 2013 It fails at compile time?
- FG (7/8) Jan 31 2013 It's because floating point literals are double by default.
void main() { float[3] v1 = [1.0, 2.0, 3.0]; // No error float[3] v = [1.0, 2.0, 3.0].dup; // Fails at runtime with error message } Why does the array assignment work when "dup" is not used. My understanding is that arrays, like classes, are references. So I declare v1 as a float[3] point it at a double[3] literal. Is v1 now a double[3] or a float[3]? Is there an implicit cast from double[3] to float[3]? The dup, gives a compile time error and if cast to float[] it gives a runtime error. This is all good, I just don't quite understand how the ref assignment is working... Thanks, Stewart
Jan 30 2013
On 2013-01-31 05:48, estew wrote:void main() { float[3] v1 = [1.0, 2.0, 3.0]; // No error float[3] v = [1.0, 2.0, 3.0].dup; // Fails at runtime with error message } Why does the array assignment work when "dup" is not used. My understanding is that arrays, like classes, are references.There are dynamic arrays and static arrays. Dynamic arrays are reference types, static arrays are value types. You have declared a static array. http://dlang.org/arrays.html -- /Jacob Carlborg
Jan 30 2013
There are dynamic arrays and static arrays. Dynamic arrays are reference types, static arrays are value types. You have declared a static array. http://dlang.org/arrays.htmlGot it. Thanks very much for the help.
Jan 31 2013
On 01/31/2013 05:48 AM, estew wrote:void main() { float[3] v1 = [1.0, 2.0, 3.0]; // No error float[3] v = [1.0, 2.0, 3.0].dup; // Fails at runtime with error message } ...It fails at compile time? The reason is that array literals have special conversion rules: Eg: bool[] x = [0,1,0,1,0,1,1]; An array literal is converted element-wise. This means an array literal sometimes behaves differently from other expressions of the same type: import std.stdio; void main() { int[] a = [0,2,0,1]; bool[] x = cast(bool[])[0,2,0,1]; bool[] y = cast(bool[])a; writeln(x,"\n",y); } [false, true, false, true] [false, false, false, false, true, false, false, false, false, false, false, false, true, false, false, false]
Jan 31 2013
On 2013-01-31 10:47, Timon Gehr wrote:The reason is that array literals have special conversion rulesIt's because floating point literals are double by default. In the first assignment float type can be deduced from v1. To make the second one work, you can explicitly make them float: float[3] v1 = [1.0, 2.0, 3.0]; float[3] v = [1.0f, 2.0f, 3.0f].dup; or duplicate v1: float[3] v = v1.dup;
Jan 31 2013