有什么理由只传递第一个元素而不传递整个数组? [英] Any reason to pass just the first element instead of the whole array?

查看:78
本文介绍了有什么理由只传递第一个元素而不传递整个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以昨天我有一个同事走进我的办公室,问我一个关于他必须使用的Fortran代码的问题。

Okay, so yesterday I had a co-worker coming into my office and asking me a question about Fortran code that he had to work with.

基本上,他使用的代码具有一个长的多维数组,并且一个子例程仅将这个长的多维数组作为参数。

Basically, the code that he works with has a long, multidimensional array, and a subroutine that expects just this long, multidimensional array as a parameter.

但是,仅调用该子例程的代码传递数组的第一个元素。代码仍然有效。所以他问我怎么可能。

However, the code calling that subroutine only passes the first element of the array. Yet the code works. So he asked me how that could be.

我还没有看到他的特定代码,但这是一个示例,说明了我如何理解这个问题(它确实有效!):

I haven't seen his particular code, but here's an example how I understand the issue (and it works!):

subroutine print_array(a)
    implicit none
    integer :: a(10)
    write(*, *) a
end subroutine print_array

program passing
    implicit none
    integer :: i(10)
    i = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /)
    call print_array(i(1))
end program passing

所以我告诉他,Fortran顺序存储数组,并且数组的位置与第一个元素相同,并且由于子例程期望某种形状,

So I told him that Fortran stores arrays sequentially, and the location of the array is the same as to the first element, and since the subroutine expects a certain shape, it knows how far to read along this sequence, and so on.

我还告诉他这是不好的编程习惯,他不应该编写这种代码

I also told him that this was bad programming practice and that he shouldn't write this kind of code himself.

但是从那时起,我一直在想:为什么写这个的人为什么首先这样做?有什么理由吗? (甚至不必是一个很好的理由。)

But since then I have been wondering: Why did whoever wrote this do it this way in the first place? Is there any reason to do that? (It doesn't even have to be a good reason.)

或者我是对的,这很愚蠢而且容易出错吗?

Or am I right and this is just silly and far too error-prone?

推荐答案

您对此的解释是正确的。您对遵循这种过时的做法的反感得到了广泛的支持。

Your explanation of how this works is correct. Your aversion to following this outdated practice is widely supported.

由于这个原因,我已经忘记了(尽管很久以前我曾经这么做过-就像从酒吧开车回家和抽烟一样,每个人都做过并且什么也没想到),但最早的语言版本可能不支持将整个数组作为参数传递。也许其他人的大脑没有被烈酒,烟草和FORTRAN的强力混合所吸引(没错,大声喊出来)。

As for the reason, I've forgotten (though long ago I used to do it to -- like driving home from the pub and smoking, everyone did and thought nothing of it) but perhaps the earliest versions of the language didn't support passing the whole array as a parameter. Perhaps someone else, whose brain is not addled by the potent mix of booze, tobacco and FORTRAN (that's right, shout it out) remembers more clearly.

这篇关于有什么理由只传递第一个元素而不传递整个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆