Escaped Parenthesis and Portable Sign-extension (medium)

J. Gregory Noel greg at noel.CTS.COM
Thu Feb 22 12:53:43 AEST 1990


Mark Shepard (shepard at upas.CS.ORST.EDU) writes:
>	Say I have a variable X of some integer (char, short, int, long) type
>	Xtype_t, and that I want to print out this variable with printf()
>	in many places in my program.  Now, I want this program to be as
>	easy to maintain as possible, so I don't want to spread information
>	about the actual type of Xtype_t all throughout the program via my
>	printf() format statements....

I've encountered the same thing.  Try this:
	typedef long Xtype_t;
	#define Xtype_fmt "%ld"
	...
	Xtype_t X;
	...
	printf("The value of X is" Xtype_fmt "\n", X);

Because of the string catenation in ANSI C, this is very flexible and portable.
It can be easily extended for hex or octal formats.  (I don't really see the
need to print a signed number as unsigned (or vice versa), but this scheme can
also be extended for that as well.)  I don't know if this is the Zen solution,
but it seems the obvious way to do it, short of C++.

In fact, when the committee was running around creating all the *_t typedefs,
I wonder why they didn't mandate *_fmt #defines to permit them to be printed.
(I know, I know, "lack of current implementation experience."  But that didn't
stop them from inventing a bunch of *_t typedefs....  Was it ever discussed,
Doug?  Or would this be "quality of implementation?")
-- 
-- J. Gregory Noel, UNIX Guru       greg at noel.cts.com  or  greg at noel.uucp



More information about the Comp.lang.c mailing list