Help on input type error: passed INTEGER(4) to INTEGER(2)

Hi everyone,

I have a function that is f(x), where x is set as integer(2), intent(in) :: x

When I type f(1), it shows the following error: Type mismatch in argument 'x' at (1); passed INTEGER(4) to INTEGER(2)

I think I can fix this problem by simply changing the function setting to integer(4), intent(in) :: x.

However, as a newbie in Fortran, I wonder how can I input “1” as an integer(2).

Thanks so much, and I look forward to hearing from you!

Best,
Long

The general way to express a constant with a kind that is not the default kind is <value>_<kind>.

1_2 is therefore 1 as an integer(2)

It can be more readable to use a constant:

integer, parameter :: ik2=2
call f(1_ik2)

But some constants are readily available in the iso_fortran_env module:

use iso_fortran_env, only : int16
call f(1_int16)
...
...
subroutine f(x)
use iso_fortran_env, only : int16
integer(int16), intent(in) :: x
1 Like

Thanks, @PierU! This is super helpful!

It is a bad idea to hard code literal kind values, for a variety of reasons. You might also want to combine the two approaches suggested by @PierU with something like:

use iso_fortran_env, only : ik2 => int16
!...
call f(1_ik2)

Then if you do ever want to change the kind, you would just need to change it a single time in the use statement rather than in all the declarations and constants throughout the code.

1 Like

It is indeed a bad idea and placing “magic numbers” in code is Magic number (programming) - Wikipedia a bad idea in programming in general.

Named constants are the way to go even if one decides to set the value just to 2 instead of int16 in a top-most module.