Check argument values at compile-time?

Check argument values at compile-time?

Hi there,
is it possible to write a subroutine / function which 1) only accepts a discrete number of integer values as inputs and 2) allows to check this at compile time?

module test
integer, parameter :: possible_value1 = 1, possible_value2 = 2
subroutine nice_routine (number)
   integer, intent(in) :: number
end subroutine nice_routine
end module test

In this example any integer number can be passed to the subroutine. Would it be possible to change it in such a way that only "possible_value1" and "possible_value2" are accepted and a compile-time error is issued for other values?

Thanks, Franz

4 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

You can't do it quite that simply, but you could do it like this:

module my_values_mod
implicit none
public :: possible_value1, possible_value2, nice_routine
type my_value_type
integer val
end type my_value_type
type(my_value_type), parameter :: possible_value1 = my_value_type(1)
type(my_value_type), parameter :: possible_value2 = my_value_type(2)
subroutine nice_routine (number)
type(my_value_type), intent(in) :: number
print *, number%val
end subroutine nice_routine
end module my_values_mod
program test
use my_values_mod
call nice_routine(possible_value1)
call nice_routine(possible_value2)

The caller of nice_routine can't construct or pass any values other than the ones you defined in the module, since the type is private. (Making the components private too is unnecessary here, but it doesn't hurt.

Steve - Intel Developer Support


Are private types within a module tagged with a signature of the module name?

IOW is (private) type(my_value_type) inside my_values_mod different from type(my_value_type) inside your_values_mod?
As well as different from type(my_value_type) declared in the scope of a program, subroutine, function?

Jim Dempsey


As long as the type is private, its name does not "leak out" of my_values_mod", so it does not interfere with the same name used for any other identifier in another module (or even in the main program.) If the type was not private, then it would be an error to use both my_values_mod and your_values_mod when the name my_values_type was referenced.

Steve - Intel Developer Support

Leave a Comment

Please sign in to add a comment. Not a member? Join today