I would like to have some clarifications about the way Fortran handles \"empty\" characters in strings. Let us assume we have this situation:
program main
implic
Standard strings in Fortran are fixed length. If you don't use the entire string, they are padded on the end with blanks/spaces.
I altered your example program to pass compiler checks of gfortran and ifort. Your function had no return, so better as a subroutine. The compilers noticed the inconsistency between the lengths of the actual and dummy argument -- because I put the procedure into a module and use
ed it so that the compiler could check argument consistency. They complain about passing a length 2 string to a length 10 string. How are the remaining characters supposed to be defined?
module test_mod
contains
subroutine test(name)
implicit none
character(10) :: name
character(3) :: cutname
write(*,*) '-'//name//'-' ! Gives output "-AB -"
! Space has then been added at the end
cutname(1:3) = name(1:3)
write(*,*) '1-'//cutname//'-' ! Gives output "-AB -"
! It seems there is a space then at the end
! of cutname
write(*,*) (cutname(1:2) == 'AB') ! Gives output T (true)
write(*,*) (cutname(3:3) == ' ') ! Gives output F (false)
write(*,*) (cutname == 'AB ') ! Gives output F (false)
end subroutine test
end module test_mod
program main
use test_mod
implicit none
call test('AB ')
end program
When I run this version, the outputs are T, T and T, which is what I expect.
EDIT: I suggest using full warning and error checking options of your compiler. That is how I quickly found the issues with the example. With gfortran: -O2 -fimplicit-none -Wall -Wline-truncation -Wcharacter-truncation -Wsurprising -Waliasing -Wimplicit-interface -Wunused-parameter -fwhole-file -fcheck=all -std=f2008 -pedantic -fbacktrace
.
A string assignment statement doesn't require the two sides to have the same lengths. If the RHS is shorter than the string variable on the LHS, it will get padded on the end with blanks. Here, the arguments should be consistent, including in length.