user1543042
user1543042

Reputation: 3440

Fortran Type in Decleration

I have a custom type and I want to place a value in approximately the same place as where I am defining the custom type like I can with a standard type. I understand this isn't a clear description so I can define a value for MyInt and the first program will compile but the second one will not.

Thank you,

John

Will compile

program test
type :: MyType
    integer MyInt
end type MyType

integer :: MyInt = 2
type(MyType) :: a
a%MyInt = 3

write(*,*) a%MyInt, MyInt

end program test

Won't compile

program test
type :: MyType
    integer MyInt
end type MyType

type(MyType) :: a
a%MyInt = 3
integer :: MyInt = 2

write(*,*) a%MyInt, MyInt

end program test

Upvotes: 0

Views: 98

Answers (2)

Yossarian
Yossarian

Reputation: 5471

In your comment to Kyle, you asked how you can declare a new variable after initialising a variable of derived type. You can do that by initialising a on the same line you declare it. The syntax is:

type(MyType) :: a = MyType(3)

You can even initialise types with multiple components in the same way:

type NewType
    integer :: MyInt
    character(len=20) :: name
end type

type(NewType) :: b = NewType(7, "Foo")

The arguments to the type constructor are passed in the same order they are declared in the type specification, or with keyword arguments:

type(NewType) :: c = NewType(name="bar", MyInt=12)

Upvotes: 2

Kyle Kanos
Kyle Kanos

Reputation: 3264

It's because of these two sequential lines:

a%MyInt = 3
integer :: MyInt = 2

You are trying to declare a new variable MyInt after you gave a%MyInt a value. Fortran requires you to put all the variable declarations first and later define the variables.

Upvotes: 2

Related Questions