jkp
jkp

Reputation: 165

Fortran derived type with optional components

Is it right to have optional component in the derived type. For example, the variable 'fname_new' in the code snippet below. If not, what is the way around? I want to include 'fname_new' optionally depending upon whether the source is of type 1 or 2.

TYPE, PUBLIC :: species
  CHARACTER(LEN=12) :: spname
  CHARACTER(LEN=12) :: source
  CHARACTER(LEN=20) :: fname
  CHARACTER(LEN=12) :: field
  CHARACTER(LEN=20),OPTIONAL :: fname_new
END TYPE species

Upvotes: 2

Views: 350

Answers (1)

ptb
ptb

Reputation: 2148

The number of components must be known at compile time so you cannot have an optional component. However, you can have an allocatable component. In your case:

type :: species
  ...
  character(len=:), allocatable :: fname_new
end type

A different approach would be to construct some sort of class hierarchy. This would have the benefit of encoding information in types rather than strings.

Edit: As @VladimirF pointed out, this approach requires fortran-2003.

Realistically, If the fname_new component is really only be 20 chars long, then you won't save a whole lot of space by making it an allocatable. On an x86/64 bit architecture, the allocatable will be an 8 byte pointer and will force some sort of alignment on your type that will eat a few more bytes. I might just leave it as a character(len=20).

Upvotes: 2

Related Questions