问题
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