Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28456 Discussions

The necessity of passing string length from C to Fortran or vice vera

DataScientist
Valued Contributor I
337 Views

Since C strings are NUL terminated, is there a necessity or preference to pass the length of a string along with the string to a Fortran routine? Are C strings always NUL terminated according to the C standard? Do all C compilers follow this rule and add the same NUL character to the end the C strings?

0 Kudos
1 Solution
IanH
Honored Contributor II
337 Views

The C standard defines the term string to be a sequence of terminated by a null character.  Literal strings in C always end up with an in-memory representation that has a trailing null.  The null character in the basic execution character set has to be a byte with all bits zero, or of value zero in other character sets, that practically means that the null is the same "zeroth" character.  C standard library functions that deal with strings follow the convention for literals, and require and typically (exceptions exist) produce null terminated strings.  Third party written C functions also typically follow the convention.

But whether you pass the length to Fortran or deal in Fortran with null terminated strings depends on the nature and requirements of your Fortran code - it is not a necessity.  If you pass a string from Fortran to C, a null often needs to be added along the way if the C code requires it.

Often I prefer to have the string length passed separately, but not always.

 

View solution in original post

1 Reply
IanH
Honored Contributor II
338 Views

The C standard defines the term string to be a sequence of terminated by a null character.  Literal strings in C always end up with an in-memory representation that has a trailing null.  The null character in the basic execution character set has to be a byte with all bits zero, or of value zero in other character sets, that practically means that the null is the same "zeroth" character.  C standard library functions that deal with strings follow the convention for literals, and require and typically (exceptions exist) produce null terminated strings.  Third party written C functions also typically follow the convention.

But whether you pass the length to Fortran or deal in Fortran with null terminated strings depends on the nature and requirements of your Fortran code - it is not a necessity.  If you pass a string from Fortran to C, a null often needs to be added along the way if the C code requires it.

Often I prefer to have the string length passed separately, but not always.

 

Reply