Is this documented behaviour?
Tyler Jameson Little
beatgammit at gmail.com
Sat Jul 27 08:14:00 PDT 2013
On Wednesday, 24 July 2013 at 15:14:16 UTC, John Colvin wrote:
> On Tuesday, 23 July 2013 at 16:34:54 UTC, John Colvin wrote:
>> void foo(ref int a)
>> {
>> a = 5;
>> }
>>
>> void main()
>> {
>> int a = 0;
>> int* aptr = &a;
>>
>> foo(*aptr);
>> assert(a == 5);
>>
>> a = 0;
>>
>> int b = *aptr;
>> foo(b);
>> assert(b == 5);
>> assert(a == 0);
>> }
>>
>> The fact that adding an explicit temporary changes the
>> semantics seems weird to me.
>
> Thanks for the explanations people, I have now fixed a rather
> worrying mistake in my programming knowledge: WHAT IT ACTUALLY
> MEANS TO DEREFERENCE A POINTER!
>
> Seriously, I've written programs in assembly and I still had it
> wrong. It's a wonder I ever wrote any correct code in my life.
To put the final nail in the coffin, this also works in C++:
#include "stdio.h"
void change(int & x) {
x = 4;
}
int main(int argc, char** argv) {
int a = 0;
int* aptr = &a;
change(*aptr);
printf("%d\n", a);
}
TBH, I was also a bit surprised because I assumed *aptr as an
rvalue created a temporary, but as you mentioned, that's not how
it works in assembly, so it's wrong to think it would work
differently in C/C++/D.
Thanks for the post!
More information about the Digitalmars-d-learn
mailing list