fortran select type
Fortran has a feature called "select type" that allows you to perform different actions based on the type of a variable. This can be useful when you have a variable that can take on different types and you want to handle each type differently.
Here is an example of how you can use select type in Fortran:
program select_type_example
implicit none
type :: my_type
integer :: i
real :: r
character(len=10) :: c
end type my_type
type(my_type) :: my_var
my_var%i = 10
select type (my_var)
type is (integer)
write(,) "The variable is an integer."
type is (real)
write(,) "The variable is a real number."
type is (character)
write(,) "The variable is a character."
class default
write(,) "The variable is of an unknown type."
end select
end program select_type_example
In this example, we define a type called my_type
with three components: i
of type integer, r
of type real, and c
of type character. We then declare a variable my_var
of type my_type
and assign a value to its i
component.
Next, we use the select type
construct to check the type of my_var
. Inside the select type
block, we have several type cases:
- If the type of
my_var
isinteger
, we print "The variable is an integer." - If the type of
my_var
isreal
, we print "The variable is a real number." - If the type of
my_var
ischaracter
, we print "The variable is a character." - If none of the above types match, we use the
class default
case and print "The variable is of an unknown type."
The select type
construct allows you to handle different types of variables in a concise and structured manner. It can be particularly useful when dealing with polymorphic variables or when you want to perform different operations based on the type of a variable.