DMD 1.022 and 2.005 releases

0ffh spam at frankhirsch.net
Wed Oct 10 09:10:10 PDT 2007


BLS wrote:
> Would be nice if you are willing to offer an example.
> It could also be used as example on :
> http://www.prowiki.org/wiki4d/wiki.cgi?PortingFromCxx
> thanks in advance, Bjoern

Okay, I am more a C type of person not C++, so I hope
I do not write anything wrong now... :)

I have a C++ function getting an int &a:

---<snip>---

void addTo(int &a,int b)
{
   a+=b;
}

void main()
{
   int a=5;
   addTo(a,3);
   printf("a=%i\n",a); // prints "a=8\n"
}

---<snap>---

IIRC this is really just syntactic sugar for passing
a pointer that is automatically dereferenced.
In C I replace the &a with an *a and dereference:

---<snip>---

void addTo(int *a,int b) // &a -> *a
{
   (*a)+=b; // a -> (*a)
}

void main()
{
   int a=5;
   addTo(&a,3); // a -> &a
   printf("a=%i\n",a); // prints "a=8\n"
}

---<snap>---

This has the added advantage, that at the point where the
function is called, I can see that a pointer is passed,
while in C++ I can't. That's why C++ coders so often write
(const T &ref) to avoid accidential side effects which
would be hard to find just looking at the function call.

This might work in D, although I have never tried it:

---<snip>---

void addTo(ref int a,int b)
{
   a+=b;
}

void main()
{
   int a=5;
   addTo(a,3);
   printf("a=%i\n",a); // prints "a=8\n"
}

---<snap>---

Regards, Frank



More information about the Digitalmars-d-announce mailing list