shorts becoming longs when passed to a function

utzoo!decvax!decwrl!sun!gnu utzoo!decvax!decwrl!sun!gnu
Tue Feb 1 01:36:59 AEST 1983


The statement about "parameters are passed as ints" even if they are short
does not imply that the parameter declaration ("short") is overridden.
Example:

foo(x) short x; { return; }

elsewhere...

	short s;
	foo(s);

's' is converted to int and passed to foo.  foo converts its parameter to
short and assigns that to 'x'.  At no time is 'x' considered an int; it's
just that the parameter on the (internal undefined) stack is an int.

I suspect this is done because C doesn't require (or allow!) the types of
parameters to be declared -- the compiler had better be able to make a good
guess about how to pass them.  'foo(4);' passes 4 as an int, which is
converted properly to a short before assignment to 'x'.  You can pass a
char, short, or int where any of char, short, or int is expected, and it
works.

This doesn't work very well in the general case.  Long args are passed as
long, with fun results if int != long.  Similar problems occur when passing
integers where float/double is expected, or vice verse; shades of Fortran's
old "mixed mode" arithmetic!

I hope that the evolution of C will provide a way to declare not only the
types of function results but also of arguments -- then we won't have to
pass those "0L"s to lseek, nor coerce arguments with (type) where the
compiler loses.

	John Gilmore, Sun Microsystems



More information about the Comp.lang.c mailing list