[Issue 23919] New: cast array to pointer should be illegal

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri May 12 21:41:13 UTC 2023


https://issues.dlang.org/show_bug.cgi?id=23919

          Issue ID: 23919
           Summary: cast array to pointer should be illegal
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: schveiguy at gmail.com

Casting an array to a pointer is allowed:

```d
import core.stdc.stdio;
auto str = "hello";
printf(cast(char *)str[0 .. 3]);
```

This prints "hello".

The user might think they have properly matched the requirements, but in
actuality, all they have done is accessed the pointer.

A few reasons why this is bad:

1. It's trivial (and more readable) to use `.ptr` instead of the cast
2. The cast must match the attributes or risk causing problems when code
evolves. Casting is a blunt instrument, and should be discouraged when better
alternatives exist.
3. The cast gives a false impression that something is happening underneath to
ensure the data is correct. Many C functions require pointers instead of
arrays, and this "seems" like the right answer.

I think we should deprecate this "feature". I'm not exactly sure why this was
needed in the first place.

I know a previous issue #6869 was closed as WONTFIX. I'm opening this to
hopefully reconsider the decision.

FWIW, the D discord has had a few people coming to ask why their code doesn't
work when casting a `string` to a `char *`.

I would pair such a cast error with a suggestion to use `toStringz` in the case
of string to char * conversions.

--


More information about the Digitalmars-d-bugs mailing list