const main args?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon May 12 22:59:32 UTC 2025
On Monday, May 12, 2025 1:01:49 AM Mountain Daylight Time Justin Allen Parrott via Digitalmars-d-learn wrote:
> On Friday, 12 August 2011 at 22:51:34 UTC, Andrej Mitrovic wrote:
> > That's pretty stupid, of course you want to modify the
> > arguments.
> >
> > Classic example:
> >
> > void main(string[] args)
> > {
> > args.popFront; // get rid of name
> >
> > foreach (arg; args)
> > {
> > }
> > }
>
> Shouldn’t do this
There is absolutely nothing wrong with it. It doesn't even modify anything
outside of the function, because when you copy a dynamic array (as occurs
when calling a function), it's sliced - meaning that each dynamic array
refers to the same memory, but if you mutate the dynamic array itself (as
opposed to its elements), it will not affect any other dynamic array which
is a slice of those same elements. In D, a dynamic array is effectively
struct DynamicArray(T)
{
size_t length;
T* ptr;
}
So, when it's copied, its ptr and length are copied, but the data is not
copied. So, popping elements off of the array has no effect on other dynamic
arrays. It just affects the length and ptr fields of that specific dynamic
array.
If you want to better understand D's dynamic arrays, then I'd suggest that
you read https://dlang.org/articles/d-array-article.html
It unfortunately doesn't use the official terminology (T[] is both a dynamic
array and a slice per the spec, but the article refers to T[] as the slice,
and the memory it points to as the dynamic array), but it does a good job of
explaining the mechanics of what's going on.
In any case, because main accepts string[], mutating the array itself has no
effect on the array that was passed in. Mutating the array's elements would,
but because their type is string, they're immutable (since string is an
alias for immutable(char)[]), meaning that they can never be mutated. So,
mutating args will have no effect whatsoever on the function calling D's
main (which is probably C's main as generated by the compiler, though there
might be functions in between depending on the current implementation).
And FYI, the post that you responded to was from 2011. I'm guessing that you
found it via searching, but given its age, the folks who were in that thread
likely don't even remember that it exists.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list