Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29434 Discussions

When a function returns a derived data type

slialgor
Beginner
1,002 Views
In order to access the member variables of a derived data returned by a function, do I have to assign it to a local variable or I can use it directly.
For example,

function A returns B, which has a member variable called C
Can I write it in A()%C?
Or I must go

type(b) :: D

D=A()
D%C

Thanks.

0 Kudos
5 Replies
Steven_L_Intel1
Employee
1,002 Views
The latter. There is no available syntax in Fortran to reference components of a function result.
0 Kudos
Arjen_Markus
Honored Contributor II
1,002 Views

Note that you can do the following:

call examine_result( f(....) )

subroutine examine_result( r )
type(some_type) :: r
a = r%a
end subroutine

This is especially useful if the result of the function is an array whose length depends on the data you feed the function:

call examine_result( pack( values, values > 0.0 ) )

Regards,

Arjen

0 Kudos
slialgor
Beginner
1,002 Views
Thanks, Steve.
Just wonder why.
It's because this causes bad performance or memory management issue or bad coding style or something else?

As you know, in object-orinted derived data type, this feature makes coding very easily. Otherwise, lots of local variables must be declared.

Thanks.
0 Kudos
Steven_L_Intel1
Employee
1,002 Views
The language standards committee did once consider such a thing, but it didn't make it into the standard.
0 Kudos
jimdempseyatthecove
Honored Contributor III
1,002 Views
To expand on Arjen's comment, consider the following:

[fortran]! compile with preprocessor enabled
module mod_foo type obj real :: a,b,c end type obj type(obj), target :: x,y,z contains ! function to return pointer to persistant object function foofoo(pick) type(obj), pointer :: foofoo integer :: pick nullify(foofoo) if(pick == 1) foofoo => x if(pick == 2) foofoo => y if(pick == 3) foofoo => z end function foofoo ! functions to return referenct to member variables real function fooA(afoo) type(obj) :: afoo fooA = afoo%a end function fooA real function fooB(bfoo) type(obj) :: bfoo fooB = bfoo%b end function fooB real function fooC(cfoo) type(obj) :: cfoo fooC = cfoo%c end function fooC end module mod_foo ! *** do not place the #define in mod_foo, place in source using mod_foo
! *** #define is global to remainder of source file ! *** n is object index (pick) ! *** m is member variable name #define foo(n,m) foo##m(foofoo(n)) program fnptr use mod_foo x%a = 1.0 x%b = 2.0 x%c = 3.0 y%a = 4.0 y%b = 5.0 y%c = 6.0 z%a = 7.0 z%b = 8.0 z%c = 9.0 ! the following will not work ! write(*,*) foofoo(2)%b ! The following works write(*,*) fooB(foofoo(2)) ! The following is equivilent to the above write(*,*) foo(2,B) end program fnptr [/fortran]

Jim Dempsey
0 Kudos
Reply