Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can D return 0 on success and non-zero on failure if main is void?

Tags:

d

In D, the main function is defined:

void main(/*perhaps some args but I do not remember*/)
{

}  

I know for sure that this function returns zero on success and non-zero on failure and yet it is defined as not returning anything. What is the logic behind it?

like image 754
There is nothing we can do Avatar asked Oct 08 '10 07:10

There is nothing we can do


1 Answers

What Alexandrescu is saying is simply shorthand for the exit code I described. The zero or nonzero returned to the OS is a (language-agnostic) process exit code, not a function return value. The OS doesn't call main directly, and main doesn't return directly to the OS. The D compiler inserts startup and shutdown code in your program to handle these interactions with the OS, as do pretty much all other compilers for other languages. On startup, for instance, this boilerplate code uses some OS-dependent mechanism to get the command-line arguments, and puts them into a D string[] array to pass to main. On shutdown, it uses the return value from int main for the exit code, or, for void main, uses its own value (0 for success, nonzero for unhandled exception).

In pseudocode:

// Generated by compiler
void _realMain()
{
    // OS-dependent; probably calls GetCommandLineW
    // and CommandLineToArgvW on Windows, for example
    string[] cmdLineArgs = createArgArray();

    int exitCode = 0;    // Assume success
    try
    {
        // static if selects only one call to main for compilation,
        // depending on main's return type.

        // If main has been written to return int, use its value for the exit code
        static if (main returns int)
            exitCode = main(cmdLineArgs);
        // If main has been declared void, just run it and keep the exit code of 0
        else
            // void main: *doesn't return anything*
            main(cmdLineArgs);
    }
    catch
    {
        // Unhandled exception results in non-zero exit code
        exitCode = 1;
        printStackTrace();
    }

    // OS-dependent process shutdown function.
    // This is where the exit code is "returned" to the OS.
    // Note it *does not* use the return keyword to do so.
    // Calling the OS's function to kill the current process
    // does not return, because the process is dead by the
    // time the function has finished!
    exitProcess(exitCode);
    // In particular, no code *after* the exitProcess line will run.
}
like image 110
anton.burger Avatar answered Oct 03 '22 06:10

anton.burger