Reputation: 3007
I am asking user to give a value at run time to do some calculations.
Both these operations are much more easier in C++ and C#, but I couldn't find a way to do that in Fortran.
Upvotes: 2
Views: 5413
Reputation: 616
I ran into the same problem where my program requires the user gives input for a missing value. The way I solved it was by having a logical variable (i.e. missing_value_set
) initialize to .false.
. Then when parsing the command arguments set the logical variable to .true.
when the required argument was indeed passed by the user. After parsing the arguments I have a check on that variable.
program main
logical :: missing_value_set = .false.
real :: MISS_VALUE = huge(1.0)
! Parse arguments
...
if (.not.missing_value_set) then
write(*, *) "ERROR: --missing argument is required"
stop
end if
! Rest of program
...
end program
No idea if that makes sense - so far it seems to work for me.
Upvotes: 0
Reputation: 29401
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).
Upvotes: 3