Automatic block between if and else/endif

I often find myself writing:

if (condition) then
  block
  integer :: some_local_variable
  ! Do something with some_local_variable only within this if scope
  end block
  ! From here some_local_variable is not available anymore
end if

But the if/end if looks like a block already, having the extra block / end block looks unnecessary.

Wouldn’t it be possible to automatically create a block in such case? Variable declaration could follow directly the then keyword:

if (condition) then
  integer :: some_local_variable
  ! Do something with some_local_variable only within this if scope
end if
! From here some_local_variable is not available anymore

This is a very minor improvement of the language, just to make things shorter.

Same would apply for for and do loops, and the case construct.

1 Like

This has been suggested on the fortran-proposals github, but it seems that it could break some existing codes: Allow declaration statements anywhere · Issue #81 · j3-fortran/fortran_proposals · GitHub

2 Likes

I am not sure this feature adds much. There are other things you could do such as:

this_block: block
  if (something) exit this_block
  ! ... lots of code
end block