2

I am asking user to give a value at run time to do some calculations.

  1. I want to test if the user entered value is a real/integer number, and if not then give a warning that the program is expecting a real/integer number here.
  2. In addition, I would as well like to know how do we check if a particular variable at the moment is null or empty. i.e. I have declared a variable but what if at the time of calculation its value is null or empty or not yet set, in that case, the program shouldn't crash instead give a warning to provide a correct value.

Both these operations are much more easier in C++ and C#, but I couldn't find a way to do that in Fortran.

milancurcic
  • 6,202
  • 2
  • 34
  • 47
Indigo
  • 2,887
  • 11
  • 52
  • 83

1 Answers1

3

I guess that "null or empty" you mean whether a variable has been initialized: "not yet set". "null" has a particular meaning for Fortran pointer variables, but I suppose that this is not your question. Fortran doesn't automatically give variables a special value before they are intentionally initialized so there is no easy way to check whether a variable has been initialized. One approach is to initialize the variable its declaration with a special value. That means that you need to know a special value that it will never obtain in the operation of the program. One possibility is to use the huge intrinsic:

program TestVar

   real :: AVar = huge (1.0)

   if ( AVar < huge (1.0) ) then
      write (*, *) "Test 1: Good"
   else
      write (*, *) "Test 1: Bad"
   end if

   AVar = 2.2

   if ( AVar < huge (1.0) ) then
      write (*, *) "Test 2: Good"
   else
      write (*, *) "Test 2: Bad"
   end if

end program TestVar

As warned by @arbautjc, this only works once, even in a subroutine. In a procedure, the initialization with declaration is only done with a first call. Also, if you change the variable type from this example, be sure to understand how huge works (e.g., Long ints in Fortran).

Community
  • 1
  • 1
M. S. B.
  • 28,968
  • 2
  • 46
  • 73