Reputation: 5470
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?
Upvotes: 7
Views: 6408
Reputation: 730
"The problem is that my variables are array elements and have big names etc so repeating x in the above equation is cumbersome task."
Well, if this is your only problem then the simplest and cleanest solution is to use the associate
construct (I use it all the time for exactly this purpose):
ASSOCIATE( x => variable_with_really_long_name, &
y => another_one)
! some calculations here
x = x + 1
! some calculations here again
end associate
Upvotes: 6
Reputation: 18118
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 )
! ...
Upvotes: 12