not really Re: Style guides and portability

Chris Torek torek at elf.ee.lbl.gov
Thu Feb 14 21:22:30 AEST 1991


(I realize I am reopening an old discussion here, which is rather like
reopening old wounds, but . . . .)

Given: a type abstraction (e.g., `typedef xxx Bigint', where xxx is
either int or long depending on the machine), various people suggest
that one way of printing these is:

>>>>	printf("%ld", (long) bigint)

while others suggest:
>>#define BIGINT_FORMAT  "ld"

In article <554 at taumet.com> steve at taumet.com (Stephen Clamage) writes:
>The source of the problem is inherent in printf-like functions, where
>the receiving function does not know the type of the parameter being
>passed, and has to be told in an auxiliary parameter (the format string).
>Whenever you have the same piece of information kept in two places you
>have synchronization problems -- in this case the type of the parameter
>being passed is known by the compiler at the calling location, and has
>to be duplicated by the programmer independently.

All of this is true.

>Other languages have solved this problem in different ways -- none of
>them by using a printf-like function.

... and all of them have their drawbacks as well.

>In Pascal, I/O is built into the language, so you can say
>	write('the value is ', x);
>which works no matter what the numeric type of x.  This solution is
>not available in C.

Unfortunately, since I/O is built into the language, you are stuck with
whatever the language designer thought of.  Pascal, for instance, lacks
the equivalent of sprintf.  FORTRAN does not allow leading-prefix insertion
for hexadecimal numbers a la %+#x.

(Of course, the same argument works for printf, e.g., `why is there no
base-2 format?', but it is generally easier to add new formats to printf
than it is to add new syntaxes.)

>In Modula-2, there is a separate output function for each data type.

This tends to be avoided in other languages (and even in some extended
implementations of Modula-2) because it becomes verbose.  Often these
output functions also lack format directives, so there is no way to say
`this goes in a ten-space-wide field and always gets a leading sign'.

>The key to minimizing porting difficulties is to avoid the inherent
>problem in printf by one of the above solutions.  I find them cleaner
>than
>	printf(BIGINT_FORMAT, (BIGINT_TYPE) bigint);

The nice thing about BIGINT_FORMAT (equivalently, "%ld" plus a cast to
long)  is that you can get those format directives in (this bigint gets
a sign, that one gets leading zeros).

No matter what method you choose, you will eventually run across something
you forgot, so the most important thing is to make sure you can extend it.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab EE div (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list