Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Fortran variable by addition

Tags:

fortran

In my Fortran code I need to update many variables by adding something to them. For example, if x is my variable, I may need to do something like this:

x = x + 1

The problem is that my variables are array elements and have big names etc so repeating x in the above equation is cumbersome task. In Python for example we have the += operator to achieve this. Do we have something similar in Fortran?

like image 407
Peaceful Avatar asked Dec 11 '22 04:12

Peaceful


1 Answers

No, Fortran does not have this operator. However, you could implement a subroutine to do so:

elemental subroutine my_incr( var, incr )
  implicit none
  integer,intent(inout) :: var
  integer,intent(in)    :: incr

  var = var + incr
end subroutine

Then you could call that in your code:

! ...
call my_incr( x, 1 )
! ...

Due to the elemental nature of the subroutine, you can also perform this operation on arrays:

! ...
call my_incr( array(:), 1 )
! ...
like image 132
Alexander Vogt Avatar answered Jan 14 '23 07:01

Alexander Vogt