0

My IDE is:

Code::Blocks 17.12 ( with tdm-gcc-5.1.0-3 )

The example code is:

program test_code

implicit none

integer                 :: i
integer,      parameter :: nn = 3
integer                 :: tmp_array(nn)
character(11)           :: name_tmp
character(*), parameter :: fmt_tmp = '("fun_name_",i2.2)'

do i = 1, nn

! solution - if statement

  if ( i == 1 ) tmp_array(i) = fun_name_01(nn,i)

  if ( i == 2 ) tmp_array(i) = fun_name_02(nn,i)

  if ( i == 3 ) tmp_array(i) = fun_name_03(nn,i)

  write(*,*) tmp_array(i)

! solution - avoid if statement

  write( name_tmp, fmt_tmp ) i

  tmp_array(i) = name_tmp(nn,i)

  write(*,*) tmp_array(i)

end do

contains

function fun_name_01(nn_tmp,i_tmp) result(result_tmp)

  integer, intent(in)  :: nn_tmp, i_tmp
  integer              :: result_tmp

  result_tmp = nn_tmp + i_tmp

end function fun_name_01

function fun_name_02(nn_tmp,i_tmp) result(result_tmp)

  integer, intent(in)  :: nn_tmp, i_tmp
  integer              :: result_tmp

  result_tmp = nn_tmp + i_tmp

end function fun_name_02

function fun_name_03(nn_tmp,i_tmp) result(result_tmp)

  integer, intent(in)  :: nn_tmp, i_tmp
  integer              :: result_tmp

  result_tmp = nn_tmp + i_tmp

end function fun_name_03

end program test_code

After building project I got this error message:

C:\Users\aleks\Desktop\test_code\main.f95|25|Error: Unclassifiable statement

What I want to do is avoiding if statement for every function with different name. Is there any way, first to write a function name into a variable name_tmp in each step up to a do loop, and after that to use that variable as the name of the function being called?

albert
  • 8,285
  • 3
  • 19
  • 32
  • 1
    This is one of those duplicates that really isn't a duplicate in that the problem in this case seems most readily solved with a UDT `type myfun;procedure(fun_1), pointer, nopass:: fun;end type myfun` and then he could declare an array of them `type(myfun) lotsafun(3)` and then point the procedure pointers at functions `lotsafun(1)%fun=>fun_1;lotsafun(2)%fun=>fun_2;lotsafun(3)%fun=>fun_3` and then he could invoke `lotsafun(i)%fun(nn)`. Unfortunately I can't post my compilable example because the question has been closed and it doesn't really fit under the duplicates. – user5713492 Mar 09 '20 at 02:30
  • Not to mention that you can use OS functions in Linux or Windows to point a procedure pointer at a procedure named by a string as well. That doesn't seem to have been covered in the duplicates either. – user5713492 Mar 09 '20 at 02:33

0 Answers0