Reading about D: few questions

Denis Shelomovskij verylonglogin.reg at gmail.com
Sun Dec 25 01:28:31 PST 2011


25.12.2011 0:48, Mr. Anonymous пишет:
> Actually, when I think of it:
>
> int a_orig = a++;
> int[] arr_orig = arr[]++;
>
> Should be read as:
>
> int a_orig = a;
> ++a;
> int[] arr_orig = arr[];
> ++arr[];
>
> (If I'm not mistaken, it was written in the TDPL book)
>
> Which means no copy of arr is made, and both arrays (which reference to
> the same block) are affected.

OK. As I wrote: "Yes, this allocation sometimes can be optimized out but 
not always.". Consider this:
---
void main()
{
     int[] a = new int[5];
     void f(int[] b)
     {
         // Here we assume that b is unchanged a.
         // As these array differ we need a copy.
         assert(b[0] == 0);
         assert(a[0] == 1);
     }
     f(a[]++); // Note: compilation error now
}
---
Why not to rewrite `f(a[]++);` as `f(a); ++a[];`? Because postincrement 
is expected to increment its argument when it is executed. It just 
returns an unchanged copy. Analogous D code with integers illustrates this:
---
void main()
{
     int a;
     void f(int b)
     {
         assert(b == 0);
         assert(a == 1);
     }
     f(a++);
}
---


More information about the Digitalmars-d-learn mailing list