Exit in Fortran
Here’s an idiomatic Fortran example demonstrating the concept of program exit:
program exit_example
use, intrinsic :: iso_fortran_env, only: error_unit
implicit none
! This print statement will be executed
print *, "Starting the program"
! This call will terminate the program with status code 3
call exit(3)
! This print statement will never be executed
print *, "This line will not be printed"
end program exit_exampleThis 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_envmodule to access theerror_unitconstant, which is the standard error output unit. - The
implicit nonestatement is used to require explicit declaration of all variables. - We print a message to indicate the start of the program.
- We use the
exitsubroutine 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):
$ gfortran exit_example.f90 -o exit_example- Run the compiled program:
$ ./exit_example
Starting the program- Check the exit status:
$ echo $?
3The 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.