Can you rewrite the following subroutine as a function?
subroutine sub(y, x, a, b, c)
intrinsic none
real :: x, y, a, b, c
y = a*x**2 + b*x + c
end subroutine
- No, there are too many arguments. [No, the number of arguments as such is not really relevant.]
- Yes, the function signature would be
real function sub(x, a, b, c)
. [Indeed, only the argumenty
is modified.] [x] - Yes, the signature would be
real function sub(y, x, a, b, c)
[Although technically okay, it would be poor style since the intent is to return the value ofy
as the result of the function.] [x] - Yes, the function signature would be
function sub(x, a, b, c) result(y)
. [Yes, this is a good signature for the function.] [x]
Can you rewrite the following subroutine as a function?
subroutine sub(n)
intrinsic none
integer :: n, i
do i = 1, n
print *, n**2
end do
end subroutine sub
- Yes, the signature would be
logical function sub(n)
and it would always return.true.
. [Indeed, it is not really elegant, but it would be correct.] [x] - Yes, the signature of the function would be
void function sub(n)
. [No, there is novoid
type in Fortran.] - Yes, the signature would be
integer function sub(n)
and it would always return 1. [Indeed, it is not really elegant, but it would be correct.] [x] - Yes, the signature of the function would be
void function sub(n)
. [No, there is novoid
type in Fortran.]
Consider the following subroutine. When you call it with arguments 3 and 5, what is the result?
subroutine sub(a, b)
implicit none
integer :: a, b
a = 3*b
end subroutine sub
- The result will be that
a
has the value 15. [No, there is no variablea
passed as an argument to the subroutine.] - You will get a runtime error. [Indeed, this will typically generate a segmentation fault.] [x]
- You will get a compilation error. [No, this compiles just fine.]
- The result will be that
a
has the value 3. [No, there is no variablea
passed to the subroutine.]