0

In Fortran, is it possible to put a function in a common block as in: COMMON /myblock/ func (where x is some variable and func is a function).

My problem is that I would like to create a function s(x) that calls an external function func(x) but without passing func in s(x). For my project, s(x) has to be a function of only one variable, i.e., I do not want to do: function s(x,func) s=func(x)

Instead, I am hoping I could do: function s(x) common /myblock/ func s=func(x)

Or, if someone has some other suggestion using modules or something, this will be great.

Thanks in advance for any help.

o.

and then have the same common (myblock) in the subroutine that calls s(x).

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Omo
  • 1

4 Answers4

2

I don't believe that this is possible in any portable way. Some implementations may allow you to use some tricks to do it.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
2

The modern way to do this is with a pointer to a function. The pointer could be passed as an argument or, for the design of this question, placed into a module. See, for example, Function pointer arrays in Fortran

Community
  • 1
  • 1
M. S. B.
  • 28,968
  • 2
  • 46
  • 73
1

I think you are not supposed to use common blocks for this, but modules. Put your function func in a module called myfunctions and then when needed insert at use myfunctions statement and thats it.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • This is the correct answer *if* the question pertains to Fortran 90/95/2003. If it is an older dialect, it is not correct. – talonmies May 22 '11 at 16:48
  • thanks, everybody. @ja72: if I use modules, how would I "dynamically" change my function? Remember, 'func' could change with each call of s(x). – Omo May 22 '11 at 16:52
  • Here are some good resources for you: http://www.macresearch.org/advanced_fortran_90_callbacks_with_the_transfer_function http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html – Ben Hocking May 23 '11 at 00:03
1

Modern fortran standards prohibit this. From 5.5.2 of Fortran 2003:

A common-block-object shall not be ... a function name, an entry name...

And at any rate, using global variables to pass around non-constant data is just a terrible, terrible idea. As ja72 points out, you could do this with modules, but I refuse to demonstrate it with sample code.

Jonathan Dursi
  • 50,107
  • 9
  • 127
  • 158