I just started using pointers in Fortran and recently stumbled upon the fact, that pointers in Fortran can't be constant. This means, something like this is not possible:
procedure(proc_type), pointer, parameter :: fPtr => myFunc
I tried to find out the reason why this is not possible. But the only thing I found was in "Modern Fortran explained":
Note also that a constant may not be a pointer [..] since these are always variables.
But this does not explain the reason behind that. Does anyone know about this?
Because the Fortran rules say so
Fortran 2008 (ISO/IEC 1539-1:2010):
5.3.14 POINTER attribute
1 Entities with the POINTER attribute can be associated with different data objects or procedures during execution of a program. A pointer is either a data pointer or a procedure pointer. Procedure pointers are described in 12.4.3.6.
This is not compatible with constants.
Why are the rules as this? Because the authors of the standard made it so.
Why they did it like that? The answer for this is very often very simple - because nobody presented a different rule to be discussed and approved by the committee, or that some members of the committee didn't like it. You really have to ask them - J3 and SC22/WG5, but be prepared to the answer that there is no specific reason for that.
In some languages which fall in the same category, e.g. C and C++, constant pointers are possible. A constant pointer initialized to point to an integer constant
const int i = 3;
static int* const x=(int*)&i;
A constant pointer initialized to point to an integer function
int fun(){
return 1;
}
static int (* const x)()=&fun;
It would be definitely possible to allow something like that in Fortran. Contact your representative in the Fortran standards committee to suggest such a feature.
There are ways ti circumvent this restriction as shown by IanH and credondo, but this answers tries to stay i the line of the original question. Why this restriction exists?
If the pointer is declared within a module with the PROTECTED attribute, the pointer becomes constant (EDIT:) outside that module
module mod1
implicit none
procedure() :: p_target
procedure(), pointer :: ptr => null()
procedure(), pointer, protected :: ptr_protected => null()
end module mod1
program pointer_parameter
USE mod1
implicit none
ptr => p_target
ptr_protected => p_target
end program
The compiler returns the following error
gfortran -c pointer_parameter.f90
pointer_parameter.f90:6.3:
ptr_protected => p_target
1
Error: Variable 'ptr_protected' is PROTECTED and can not appear in a pointer
association context (pointer assignment) at (1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With