Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

fortran90 - Wrong result when using a global variable in Fortran

I'm learning the basics of Fortran. I created a simple subroutine initializing a matrix:

program test
   integer, parameter :: n = 1024
   real :: a(n, n)
   call init(a)
   write (*, *) a(1, 1)
end program

subroutine init(a)
   real :: a(n, n)
   a(:, :) = 3.0
end subroutine

Then the output is 0.0 instead of expected 3.0. Apart from that, valgrind says that:

==7006== Conditional jump or move depends on uninitialised value(s)
==7006==    at 0x400754: init_ (in /home/marcin/proj/mimuw/fortran/test)
==7006==    by 0x4007A4: MAIN__ (in /home/marcin/proj/mimuw/fortran/test)
==7006==    by 0x40083B: main (in /home/marcin/proj/mimuw/fortran/test)

Why? The n parameter is correctly recognized by the compiler and should be a global one.

I compiled the program with gfortran 6.3.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

n is not a global variable, it is a local variable of the main program.

The subroutine is a completely independent compilation unit from the main program and they do not share any information.

A subroutine can "see" other variables of the parent module, if it is a module procedure, or variables of a parent (host) procedure or program if it is an internal procedure.

Be sure to read about the structure of Fortran programs and use modules as much as possible. Prefer modules over internal procedures. You will see how to put the subroutine into a module or how to make it internal to the main program in the link.

I did not mention common blocks, just don't use them, they are obsolete. And rember to use implicit none in every compilation unit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...