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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With