What is the explicit difference between the fortran intents (in,out,inout)?

前端 未结 3 1533
慢半拍i
慢半拍i 2020-12-01 12:57

After searching for a while in books, here on stackoverflow and on the general web, I have found that it is difficult to find a straightforward explanation to the real diffe

3条回答
  •  渐次进展
    2020-12-01 13:10

    Intents are just hints for the compiler, and you can throw that information away and violate it. Intents exists almost entirely to make sure that you only do what you planned to do in a subroutine. A compiler might choose to trust you and optimize something.

    This means that intent(in) is not pass by value. You can still overwrite the original value.

    program xxxx  
        integer i  
        i = 9  
        call sub(i)  
        print*,i ! will print 7 on all compilers I checked  
    end  
    subroutine sub(i)  
        integer,intent(in) :: i  
        call sub2(i)  
    end  
    subroutine sub2(i)  
        implicit none  
        integer i  
        i = 7  ! This works since the "intent" information was lost.  
    end
    
    program xxxx  
        integer i  
        i = 9  
        call sub(i)  
    end  
    subroutine sub(i)  
        integer,intent(out) :: i  
        call sub2(i)  
    end  
    subroutine sub2(i)  
        implicit none   
        integer i  
        print*,i ! will print 9 on all compilers I checked, even though intent was "out" above.  
    end  
    

提交回复
热议问题