Bug 23919 – cast array to pointer should be illegal

Status
NEW
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-05-12T21:41:13Z
Last change time
2024-12-13T19:28:59Z
Assigned to
No Owner
Creator
Steven Schveighoffer
See also
https://issues.dlang.org/show_bug.cgi?id=6869
Moved to GitHub: dmd#20281 →

Comments

Comment #0 by schveiguy — 2023-05-12T21:41:13Z
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.
Comment #1 by robert.schadek — 2024-12-13T19:28:59Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/20281 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB