Consider the following snippet:
module string_mod
implicit none
character(len=8), protected, target :: str = 'abcdefgh'
contains
function ptr_to_str()
character(len=:), pointer :: ptr_to_str
ptr_to_str => str
end function
end module
program test
use string_mod
implicit none
character(len=:), pointer :: p
p => ptr_to_str()
print *, p
p = repeat('a',len(p))
print *, p
end program
Is it allowed to modify the protected variable via the pointer returned by the procedure? The constraints in 8.5.15 (J3/24-007) only talk about use association.
Paragraph 2 of 8.5.15 says:
Other than within the module in which an entity is given the PROTECTED attribute, or within any of its descendants,
- if it is a nonpointer object, it is not definable, and
Since str
is not a pointer object, I suspect what I’m doing here is “illegal”.
Related questions:
- What is PROTECTED supposed to protect for a pointer? - As explained here a
protected, pointer
variable can still be modified, the protection only applies to the pointer association status, not the target. I believe the example above is slightly different.
Output of a few compilers:
> nagfor test_protected.f90
NAG Fortran Compiler Release 7.2(Shin-Urayasu) Build 7203
[NAG Fortran Compiler normal termination]
> ./a.out
abcdefgh
aaaaaaaa
> gfortran test_protected.f90
> ./a.out
abcdefgh
aaaaaaaa