This FORTRAN code shouldn't compile. Is there a reason why it does?

邮差的信 提交于 2021-02-05 05:55:26

问题


The following code compiles, but I do not think that it should. As you can see, the output is garbage.

This is a minimal failing example of something that bit me hard in a large project I work on.

My question is - why does the compiler not complain? Is this a compiler limitation, or is this somehow "expected behaviour", and I've missed something?

I'm using gfortran 4.6.3.

module dataModule
    integer :: datum1 = int(1)
    integer :: datum2 = int(2)    
end module dataModule

program moduleTest
    use dataModule, only: datum1

    write(*,*) "datum 1 is", datum1
    write(*,*) "datum 2 is", datum2

end program moduleTest

Example output:

datum 1 is           1
datum 2 is  4.58322689E-41

回答1:


Your code is at fault, not the compiler. If datum2 were use associated despite the only clause and if the explicit initialization of datum2 were ignored, then yes, that would be a naughty compiler.

The answer is much more mundane, though.

datum2 is not use associated: in the absence of implicit none it is an implicitly typed variable in the main program. The "garbage" comes from the fact that it is not defined, by initialization or assignment, before its value is referenced and that it's implicitly (default) real. The compiler isn't required to detect this mistake at compile (or run) time.



来源:https://stackoverflow.com/questions/27321711/this-fortran-code-shouldnt-compile-is-there-a-reason-why-it-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!