5

为什么与 f90 相比,fortran 2003 中的变量没有初始化为零?

我在文件中的函数中有一个变量。它初始化为0。我想用另一个函数然后它显示一个垃圾值。即使对于全局变量也是如此。我需要为 fortran 2003 编译器设置任何选项吗?

4

4 回答 4

7

您可以尝试使用 -zero 或 /Qzero - 它们会将本地标量初始化为零 - 但您确实应该明确设置初始值。正如您所发现的,取决于编译器为您执行此操作是引入错误的好方法。请注意,不同编译器的选项名称可能不同。提到的那些是针对Intel Visual Fortran的。

于 2009-07-21T12:02:39.777 回答
4

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

于 2009-11-24T17:48:54.793 回答
3

我不熟悉任何 Fortran 编译器,但我知道一般来说,大多数编译器不会初始化全局变量和局部变量。初始化应始终在代码中完成。您不应依赖编译器为您执行此操作。您看到的垃圾可能来自堆栈或内存堆。一些编译器在分配内存时会用零填充堆,这可以解释为什么一些编译器似乎用 0 初始化变量。它们实际上并没有初始化任何东西,它们只是使用恰好被零填充的内存区域。 .

于 2009-07-21T11:51:12.793 回答
2

Fortran 90 和 Fortran 2003 在变量初始化方面没有区别。所有有效的 Fortran 90 代码都是有效的 Fortran 2003,并且应该给出相同的结果(除了极少数晦涩的极端情况,标准现在指定了依赖于编译器的行为;这不是其中之一)。

现在,至于为什么您会看到差异,如果不知道您的编译器是什么以及您的代码究竟做了什么,就很难说。我强烈怀疑你依赖于编译器的行为,当你改变编译器时它就坏了。

于 2009-07-23T08:39:51.770 回答