0

I'm trying to create function that takes a number and returns a string representation of that number. This is what I've tried:

  program test
  print *, num2str(9.0)
  end

  character(len=128) function num2str(num)
     real num
     write(num2str,*) num
  endfunction

But this returns the error:

num2str.f:1.22:

      print *, num2str(9.0)                                             
                      1
Error: Return type mismatch of function 'num2str' at (1) (INTEGER(4)/CHARACTER(1))

How could I solve this problem?

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
builder-7000
  • 7,131
  • 3
  • 19
  • 43
  • Add `implicit none` to each scoping unit. – steve Nov 27 '19 at 21:34
  • put your function in a module (foo for instance) and add a use statement (use foo) at the top of the main program. The trouble you meet comes from the fact that num2str definition is not known in the main program. – Francois Jacq Nov 27 '19 at 21:41

1 Answers1

3

Unlike with subroutines, you need to import or declare the function interface in the program scope.

Option 1

Explicitly declaring the interface:

program test
  interface
     character(len=128) function num2str(num)
       real num
     end function num2str
  end interface
  print *, num2str(9.0)
end

character(len=128) function num2str(num)
  real num
  write(num2str,*) num
endfunction

Option 2

Put the function into the program contains section, which automatically generates the interface:

program test
  print *, num2str(9.0)
contains
  character(len=128) function num2str(num)
    real num
    write(num2str,*) num
  endfunction
end

Option 3

Define the function inside a module and import that module in program test:

module m
contains
  character(len=128) function num2str(num)
    real num
    write(num2str,*) num
  endfunction num2str
end module m

program test
  use m
  print *, num2str(9.0)
end
Raul Laasner
  • 1,475
  • 1
  • 17
  • 30