www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - ABI for static arrays

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
This compiles:

void foo(int* ptr) { }
void main()
{
    int[2] arr;
    test(arr);
}

What was the use-case for making static arrays implicitly convert to a
pointer to the first element? Was this done to ease C compatibility?

It seems like it could cause trouble since static arrays lay on the
stack. A somewhat elaborate example:

import std.stdio;

void foo(int* ptr)
{
    static int* val;
    if (!val) val = ptr;
    writeln(*val);
}

void test()
{
    int[2] x = 1;
    foo(x);
}

void main()
{
    test();
    foo(null);
}

Writes:

$ 1
$ 1245036

It even works with  safe, and one of the safe rules are: "No casting
from any non-pointer type to a pointer type.". Maybe that only applies
to the function body, but I think it should probably apply to the
arguments as well.

Anyway I don't see why we need it, we can easily use arr.ptr to pass
the pointer to the first element. Unless there are good benefits, I'd
ask if any code in the wild would break if it were changed? I've
certainly never seen it used.
Feb 05 2013
parent reply Marco Leise <Marco.Leise gmx.de> writes:
Good observation. It is possibly in there to allow char arrays
aka string literals to be passed to C functions?

-- 
Marco
Feb 05 2013
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 02/06/2013 03:38 AM, Marco Leise wrote:
 Good observation. It is possibly in there to allow char arrays
 aka string literals to be passed to C functions?
I do not think so. String literals are immutable(char)[], not immutable(char)[N]. They just have special implicit conversion behaviour.
Feb 05 2013