Switch in Fortran

Here’s the translation of the given code into Fortran along with an explanation:

Switch Statements

Switch statements express conditionals across many branches.

program switch_example
    implicit none
    integer :: i
    character(len=20) :: day

    ! Here’s a basic switch.
    i = 2
    print *, 'Write ', i, ' as '
    select case (i)
    case (1)
        print *, 'one'
    case (2)
        print *, 'two'
    case (3)
        print *, 'three'
    end select

    ! Using select case with derived values.
    day = weekday()
    select case (day)
    case ('Saturday', 'Sunday')
        print *, "It's the weekend"
    case default
        print *, "It's a weekday"
    end select

    ! Using select case without an expression.
    select case (.true.)
    case (hour() < 12)
        print *, "It's before noon"
    case default
        print *, "It's after noon"
    end select

    ! A type switch is not something Fortran does directly. 
    ! However, for demonstration, let's use a simple type check.
    call whatAmI(.true.)
    call whatAmI(1)
    call whatAmI('hey')

contains

    function weekday() result(day)
        character(len=20) :: day
        ! This is a placeholder function.
        ! A proper implementation would return the current day of the week.
        day = 'Monday'
    end function weekday

    function hour() result(h)
        integer :: h
        ! This is a placeholder function.
        ! A proper implementation would return the current hour.
        h = 13
    end function hour

    subroutine whatAmI(i)
        class(*), intent(in) :: i
        select type(i)
        type is( logical )
            print *, "I'm a bool"
        type is( integer )
            print *, "I'm an int"
        type is( character(len=*) )
            print *, "Don't know type ", 'string'
        end select
    end subroutine whatAmI

end program switch_example

You can use the gfortran compiler to run this program. Save the code to a file named switch_example.f90 and then compile and run it.

$ gfortran -o switch_example switch_example.f90
$ ./switch_example
 Write 2 as 
 two
 It's a weekday
 It's after noon
 I'm a bool
 I'm an int
 Don't know type  string

In Fortran, select case is used for switch-like logic. Fortran does not directly support type-switching as some other languages, but we can use select type to achieve similar functionality. Now that we can run and build basic Fortran programs, let’s learn more about the language.