I am writing the following simple routine:
program scratch
character*4 :: word
word = 'hell'
print *, concat(word)
end program scratch
function concat(x)
character*(*) x
concat = x // 'plus stuff'
end function concat
The program should be taking the string 'hell' and concatenating to it the string 'plus stuff'. I would like the function to be able to take in any length string (I am planning to use the word 'heaven' as well) and concatenate to it the string 'plus stuff'.
Currently, when I run this on Visual Studio 2012 I get the following error:
Error 1 error #6303: The assignment operation or the binary expression operation is invalid for the data types of the two operands. D:\aboufira\Desktop\TEMP\Visual Studio\test\logicalfunction\scratch.f90 9
This error is for the following line:
concat = x // 'plus stuff'
It is not apparent to me why the two operands are not compatible. I have set them both to be strings. Why will they not concatenate?
High Performance Mark's comment tells you about why the compiler complains: implicit typing.
The result of the function
concat
is implicitly typed because you haven't declared its type otherwise. Althoughx // 'plus stuff'
is the correct way to concatenate character variables, you're attempting to assign that new character object to a (implictly) real function result.Which leads to the question: "just how do I declare the function result to be a character?". Answer: much as you would any other character variable:
[note that I use
character(len=...)
rather thancharacter*...
. I'll come on to exactly why later, but I'll also point out that the formcharacter*4
is obsolete according to current Fortran, and may eventually be deleted entirely.]The tricky part is: what is the length it should be declared as?
When declaring the length of a character function result which we don't know ahead of time there are two1 approaches:
In the case of this function, we know that the length of the result is 10 longer than the input. We can declare
To do this we cannot use the form
character*(LEN(x)+10)
.In a more general case, deferred length:
where later
Using these forms adds the requirement that the function
concat
has an explicit interface in the main program. You'll find much about that in other questions and resources. Providing an explicit interface will also remove the problem that, in the main program,concat
also implicitly has a real result.To stress:
will not work for
concat
having result of the "length unknown at compile time" forms. Ideally the function will be an internal one, or one accessed from a module.1 There is a third: assumed length function result. Anyone who wants to know about this could read this separate question. Everyone else should pretend this doesn't exist. Just like the writers of the Fortran standard.