Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 681
carthurs Avatar asked Mar 01 '26 00:03

carthurs


1 Answers

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.

like image 121
francescalus Avatar answered Mar 02 '26 13:03

francescalus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!