Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

scaler argument instead of array

anishtain4
Beginner
544 Views
assume that I have written a subroutine that its argument should be an array but in a special case it can be an scaler, like:

subroutine sqr(x)
real,intent(inout) ::x(:)
x**2
end subroutine

but I call it like:

real ::x
x=2.
call sqr(x)

I know this lead to an error and I know interface can solves my problem but is there any other way that I do this with merely one subroutine?
0 Kudos
3 Replies
mecej4
Honored Contributor III
544 Views
>"...is there any other way that I do this..."

It is not clear what you meant by "this". What is it that you want to do, and why is it important to go around the rules of the language?

Obviously, it is possibly to delude the compiler by giving it an incorrect interface (either actively or passively, by omission). Sometimes, you can even get away without paying a penalty, as in the case of passing (by address) a scalar actual argument when the dummy is declared to be an array.

A caller must provide an explicit interface in order to call a subroutine that expects assumed-shape arrays. Not doing so is a more significant error than using a scalar actual argument in place of a an expected array.

Consider this simple explanation for the requirement: the declaration of argument as an assumed-shape array -- with (:,..) as the extent -- is a declaration to the compiler that the caller will make available certain information about the extents of the array. If this promise is not kept, the caller will use the junk values in the memory locations where that information is expected to exist, and the program is almost certain to go astray.

Therefore, even a modified version of your code excerpt with

real :: x(2)
x = 2.
call sqr(x)

would still be illegal code if an explicit interface is not available to the caller.
0 Kudos
tom_p
Beginner
544 Views
Try using an elemental subroutine:

[bash]program test

  implicit none

  real :: a, b(2)

  a = 2
  b = 2
  call sqr(a)
  call sqr(b)

  print *, "a", a
  print *, "b", b


contains

  elemental subroutine sqr(x)
    real, intent(inout) :: x
    x = x**2
  end subroutine sqr

end program test
[/bash]
0 Kudos
Jugoslav_Dujic
Valued Contributor II
544 Views
Look up ELEMENTAL keyword in your textbook. Or see the entry on Fortran wiki.
0 Kudos
Reply