DMD 0.170 release
Bill Baxter
dnewsgroup at billbaxter.com
Tue Oct 17 21:03:51 PDT 2006
Tom S wrote:
> Bill Baxter wrote:
>> Seriously? Is there no way to write the function below so that the
>> program prints out the same value twice?
>>
>> void print_addr( ??? arg )
>> {
>> writefln(&arg);
>> }
>>
>> void main()
>> {
>> int[] arr = [1,2,3,4,5];
>> writefln(&arr);
>> print_addr(arr);
>> }
>
> Sure it's possible, but in the earlier case, you were trying to access
> stack variables after returning from the function. In the same manner,
> 'arg' is no longer a valid variable after print_addr returns, you'd be
> referencing junk on the stack. You could store it in a static variable,
> but I consider it hackish, as it's not thread safe :)
Right, but really I don't want to access 'arg' I want to access the
'arr' in the outer scope.
In C++ I would just make it a reference parameter, and take the address:
void print_addr( IntArrayType& arg )
{
writefln(&arg);
}
void main()
{
int[] arr = [1,2,3,4,5];
writefln(&arr);
print_addr(arr);
}
Then aside from the fact that D is not C++, it would print the same
value for both, and it wouldn't be accessing a static variable. And it
would be perfectly thread safe.
--bb
More information about the Digitalmars-d-announce
mailing list