ravi
ravi

Reputation:

Variables not initialized in Fortran 2003

Why the variables are not initializing to zero in fortran 2003 when compared with f90?

I have a variable in a function from a file. its initialized to 0. I want to use it another function then it shows a garbage value. even for global variables also. Is there any option I need to set for fortran 2003 compiler?

Upvotes: 4

Views: 3331

Answers (4)

John Reynolds
John Reynolds

Reputation: 85

We experienced this moving from Compaq Visual Fortran to Intel Visual Fortran. Notwithstanding his lack of familiarity with Fortran compilers, the entire post left by Workshop Alex is correct--you shouldn't rely on the compiler setting initial values. The Standard doesn't say variable values should automatically be set. Even if it did, relying on this compiler behavior is risky.

Compaq Visual Fortran automatically initializes variables. Other compilers do not. Your code needs to be fixed. You can only do that by initializing all your variables.

John

Upvotes: 4

F'x
F'x

Reputation: 12298

There is no difference between Fortran 90 and Fortran 2003 in initialisation of variables. All valid Fortran 90 code is valid Fortran 2003, and should give the same result (except for very few obscure corner-cases where what was compiler-dependant behaviour is now specified by the standard; this is not one of those).

Now, as to why you could see a difference, it's hard to say without knowing what your compilers are, and what your code does exactly. I strongly suspect you were relying on compiler-dependant behaviour, and it broke when you changed compiler.

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532435

You could try using -zero or /Qzero -- these will initialize local scalars to zero -- but you really should be explicitly setting initial values. Depending on the compiler to do it for you is, as you have found out, a good way to introduce bugs. Note that the option names may be different for different compilers. The ones mentioned are for Intel Visual Fortran.

Upvotes: 6

Wim ten Brink
Wim ten Brink

Reputation: 26682

I'm unfamiliar with any Fortran compiler but I do know that in general, most compilers won't initialize global and local variables. Initialization should always be done in code. You should not rely on the compiler to do this for you. The garbage you're seeing is probably from the stack or memory heap. Some compilers will fill the heap with zero's when allocating memory which could explain why some compilers will seem to initialize variables with 0. They haven't actually initialized anything, they're just using a memory area that happened to be filled with zero's...

Upvotes: 3

Related Questions