October 21, 2014
On 10/21/2014 05:22 AM, edn wrote:> Could someone provide me with examples showing the usefulness of
> pointers in the D language? They don't seem to be used as much as in C
> and C++.

A pointer is the only sensible option for the following:

- References to any local data because 'ref' is only for parameters and return types.

    int a;
    int b;
    int* r = (condition ? &a : &b);    // r must be a pointer
    *r = 42;

- Any link in a linked data structure like linked lists and trees:

struct L
{
    L* next;    // must be a pointer
}

One can use classes and slices for references as well but they are more expensive.

Ali

October 21, 2014
Ali Çehreli:

> - References to any local data because 'ref' is only for parameters and return types.
>
>     int a;
>     int b;
>     int* r = (condition ? &a : &b);    // r must be a pointer
>     *r = 42;

Regarding this example, this works:

void main() {
    int a, b;
    bool condition;
    (condition ? a : b) = 42;
}

Bye,
bearophile
October 21, 2014
On 10/21/2014 01:15 PM, bearophile wrote:
> Ali Çehreli:
>
>> - References to any local data because 'ref' is only for parameters
>> and return types.
>>
>>     int a;
>>     int b;
>>     int* r = (condition ? &a : &b);    // r must be a pointer
>>     *r = 42;
>
> Regarding this example, this works:
>
> void main() {
>      int a, b;
>      bool condition;
>      (condition ? a : b) = 42;
> }
>
> Bye,
> bearophile

Yes but that doesn't scale when we need to use it again:

  (condition ? a : b) = 42;
  foo(condition ? a : b);
  // ...

Ali

October 21, 2014
Am 21.10.2014 um 14:47 schrieb monarch_dodra:
> On Tuesday, 21 October 2014 at 12:22:54 UTC, edn wrote:
>> Could someone provide me with examples showing the usefulness of
>> pointers in the D language? They don't seem to be used as much as in C
>> and C++.
>
> The only difference between C/C++ and D is that C uses pointers for both
> "pointer to object" and "pointer to array", whereas D has a "slice" object.
>
> C++ introduced "pass-by-ref" (also exists in D), which has tended to
> reduce the (visible) use.
>

Actually it goes back to Algol and all languages in the Pascal family support it.

--
Paulo

1 2
Next ›   Last »