Exit in Fortran
Here’s an idiomatic Fortran example demonstrating the concept of program exit:
This Fortran program demonstrates how to exit a program with a specific status code. Here’s a breakdown of the code:
- We define a program named
exit_example
. - We use the
iso_fortran_env
module to access theerror_unit
constant, which is the standard error output unit. - The
implicit none
statement is used to require explicit declaration of all variables. - We print a message to indicate the start of the program.
- We use the
exit
subroutine to terminate the program with a status code of 3. - The last print statement will never be executed because the program exits before reaching it.
To compile and run this program:
- Save the code in a file named
exit_example.f90
. - Open a terminal and navigate to the directory containing the file.
- Compile the code using a Fortran compiler (e.g., gfortran):
- Run the compiled program:
- Check the exit status:
The output shows that the program prints the first message and then exits with status code 3. The second print statement is never executed.
In Fortran, unlike some other languages, the exit
subroutine is used to terminate the program with a specific status code. This is similar to the os.Exit()
function in Go or the exit()
function in C.
It’s important to note that Fortran doesn’t have an exact equivalent to Go’s defer
statement. In Fortran, you need to be careful about resource cleanup and ensure that any necessary finalization is done before calling exit
.
This example demonstrates how to exit a Fortran program with a specific status code, which can be useful for indicating success or failure to the calling environment.