Setting default values for Main function's args Array

Paul Backus snarwin at gmail.com
Thu Jun 27 17:20:37 UTC 2019


On Thursday, 27 June 2019 at 17:05:05 UTC, Vaidas wrote:
> Is it possible to set the default values for the Main 
> function's arguments?
> It seems that I'm getting Range error.
>
>>import std.stdio : writeln;
>>void main(string[] args = ["asdsfasdf", "asdklfajsdk", 
>>"asdfasdfasd"]){
>> 
>>    writeln("", args[1]);
>>}
>
> Output:
>>vaidas at vaidas-SATELLITE-L855:~/Desktop$ rdmd newfile.d
>>>core.exception.RangeError at newfile.d(4): Range violation
>>----------------
>>??:? _d_arrayboundsp [0x555f5b79f8e9]
>>??:? _Dmain [0x555f5b79e7ee]

Your main function is receiving an empty array as an argument, 
which overrides the default argument.

The correct way to do what you want to do is this:

void main(string[] args)
{
     string[] defaultArgs = ["my", "default", "arguments"];
     if (args.length == 0) {
         args = defaultArgs;
     }
     // Process args...
}


More information about the Digitalmars-d-learn mailing list