Using results of impure functions in automatic allocation (nvfortran)

Consider the following minimal working example:

module lib
    type t
    contains
        procedure::f,g,h
    end type
contains
    integer function f(this)
        class(t),intent(in)::this
        real::r
        ! adding the following calculation to avoid inlining of the function result in the function calls
        call RANDOM_NUMBER(r)
        f=42*(1+r)
        print*,"I'm an impure function"
    end
    function g(this)result(c)
        class(t),intent(in)::this
        ! using the result of an impure function for automatic allocation of a CHARACTER variable
        character(len=this%f())::c
        c='42'
    end
    function h(this)result(a)
        class(t),intent(in)::this
        ! using the result of an impure function for automatic allocation of an array
        integer::a(this%f())
        a=42
    end
end

program prog
    use lib
    type(t)::o
    print*,o%g()
    print*,o%h()
end

A smaller example was already discussed here. The Fortran standard doesn’t allow using the results of impure functions for automatic allocation of CHARACTER variables or arrays. But the code above compiles successfully with the Nvidia compiler (nvfortran 22.9 on Ubuntu 18.04.2 LTS).

I suppose, it is a compiler bug, because running the compiled code leads to unexpected behavior: the message I'm an impure function is printed 4 times, even though the function f is called only twice.

Thanks vlad0dalv.

I’ve filled a problem report, TPR #33181, and sent it to engineering for investigation.

-Mat

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.