用 -xalias=overindex 编译以下示例
integer a,z common // a(100),z z = 1 call sub(a) print*, z subroutine sub(x) integer x(10) x(101) = 2 编译器假设对 sub 的调用可以写入 z 用 -xalias=overindex 编译时,程序打印 2 而非 1 |
索引越界在很多传统 Fortran 77 程序中都会出现,应予以避免。在很多情况下,结果将无法预料。要确保正确性,应使用 -C(运行时数组边界检查)选项编译和测试程序,以标记任何数组下标问题。
一般而言,overindex 标志只能与传统 Fortran 77 程序一起使用。-xalias=overindex 不适用于数组语法表达式、数组段、WHERE 和 FORALL 语句。
为确保生成代码的正确性,Fortran 95 程序应该总是符合 Fortran 标准中的下标规则。例如,下例的一个数组语法表达式中使用了二义性下标,该表达式因数组索引越界将始终产生不正确的结果:
本例中数组语法索引越界不会产生正确的结果! parameter (n=10) integer a(n),b(n) common /qq/a,b integer c(n) integer m, k a = (/ (i,i=1,n) /) b = a c(1) = 1 c(2:n) = (/ (i,i=1,n-1) /) m = n k = n + n C C the reference to a is actually a reference into b C so this should really be b(2:n) = b(1:n-1) C a(m+2:k) = b(1:n-1) C or doing it in reverse a(k:m+2:-1) = b(n-1:1:-1) 从直观上,用户期望数组 b 现在与数组 c 相似,但结果是无法预料的 |
xalias=overindex 标志无助于此种情况,因为 overindex 标志没有扩展至数组语法表达式。此例虽然可以编译,但不会给出正确结果。用等价的 DO 循环替换数组语法,改写本例,在用 -xalias=overindex 进行编译后,就正常了。但应完全避免这种编程习惯。