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_example

This Fortran program demonstrates how to exit a program with a specific status code. Here’s a breakdown of the code:

  1. We define a program named exit_example.
  2. We use the iso_fortran_env module to access the error_unit constant, which is the standard error output unit.
  3. The implicit none statement is used to require explicit declaration of all variables.
  4. We print a message to indicate the start of the program.
  5. We use the exit subroutine to terminate the program with a status code of 3.
  6. The last print statement will never be executed because the program exits before reaching it.

To compile and run this program:

  1. Save the code in a file named exit_example.f90.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the code using a Fortran compiler (e.g., gfortran):
$ gfortran exit_example.f90 -o exit_example
  1. Run the compiled program:
$ ./exit_example
Starting the program
  1. Check the exit status:
$ echo $?
3

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.