varargs fails on typedefs

Brett Galloway brett at wjvax.UUCP
Tue Jul 29 08:54:41 AEST 1986


I have a complaint about the a shortcoming of the standard varargs
package (to allow use of variable nos. of arguments).  The varargs package
uses a line of the form

	var = va_arg(va,<type>)

to grab the next (variable) argument, where va is the variable argument
pointer maintained by the varargs package, and <type> is the type of the
next argument.

The problem is related to C's argument promotion; namely, that it promotes
char and short arguments to int's and float to double.  Because the varargs
package is a macro package, an expression of the form

	var = va_arg(va,short)

fails, because, even if the caller tried to pass a short, it got converted
to an int, and the va_arg macro will fail because it will not pick up all
the bits of the int (assuming (sizeof(short) < sizeof(int))).  So far, this
is not deadly; you just remember never to have variable arguments that
are "promotable"; i.e., always use int's or double's.

The problem appears when you use a typedef.  Depending on whether the
typedef was promotable or not, a variable argument of the type will or
will not fail.  For example, I may do the following:

	typedef	int	NUMBER;
	...
	NUMBER	val;
	...
	foo(val);
	...
	foo(va_alist)
	va_dcl
	...
	NUMBER	value;
	...
	value = va_arg(va,NUMBER);

the latter part of this fragment is a function foo() with a variable
argument of type NUMBER.  If, in fact, NUMBER was an int, this will work.
If NUMBER was a short, it will fail.  This makes the typedef completely
useless.

To fix this problem, I propose a promote() operator, as follows:

	"promote(char)" => "int"
	"promote(short)" => "int"
	"promote(int)" => "int"
	"promote(float)" => "double"
	"promote(NUMBER)" => <whatever NUMBER typedef'd as>
	etc.

An operator like this is REQUIRED to write a varargs package that works
with typedef'd types.  Note that there is NO way to emulate promote() with
a macro.

-- 
-------------
Brett Galloway
{pesnta,twg,ios,qubix,turtlevax,tymix,vecpyr,certes,isi}!wjvax!brett



More information about the Comp.lang.c mailing list