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?
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 )
! ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With