Segfault when calling a function with a constant argument

前端 未结 5 447
一个人的身影
一个人的身影 2020-12-21 13:58

I have written this very simple code in Fortran:

program su
  implicit none
  real ran3
  write(*,*) ran3(0)
end program su

real*8 function ran3(iseed)
  im         


        
5条回答
  •  既然无缘
    2020-12-21 14:21

    If you want, for whatever reason, that your iseed is modified by the function, you should mark it with intent(in out). If you do so, the compiler will trigger an error at compile time when you call the function using a literal constant. If you want to use the parameter just as input, you can mark it as intent(in), and you will get again an error since you are assigning iseed inside your function.

    I think it can be a good idea to get the habit of declaring the intent.

    Your code could look like

    program su
        implicit none
    
        write(*, *) ran3(0)
    
    contains
    
      function ran3(iseed)
        implicit none
        real :: ran3
        integer, intent(in) :: iseed
        ! or intent(in out) :: iseed
    
        iseed = iseed*153941+1
        ran3 = float(iseed)*2.328+0.5     
      end function ran3
    
    end program su
    

    (this won't compile no matter if you use "in" or "in out" as intent, because of what explaned early).

    The following instead will compile (and should work, too)

    program su
        implicit none
    
        write(*, *) ran3(0)
    
    contains
    
      function ran3(iseed)
        implicit none
        real :: ran3
        integer, intent(in) :: iseed
    
        ran3 = real(iseed*153941+1)*2.328+0.5     
      end function ran3
    
    end program su
    

提交回复
热议问题