[comp.lang.c] Returning several values

GAY%CLSEPF51.BITNET@CUNYVM.CUNY.EDU (03/10/88)

To return several values from a function: what's wrong with using

struct foo {
  int a, b;
};

struct foo fun(a, b)
int a, b;
{
    struct foo temp;

    temp.a = a / b; temp.b = a % b;

    return(temp);
}

I know this isn't as elegant as the proposed method (you have to extract
the values from the struct, declare a special purpose structure ...), but
it works and exists in at least one implementation of C (Lattice C). I
don't know if this is in the ANSI standard, if it isn't it is a fairly
logical extension (not needing any new syntax such as the square brackets
proposed), and it can even qualify as having prior use ! (I have a vague
memory of seeing this feature in other C compilers, but as I've never used
many I'm not sure if it is widespread or not (In other words, I hope I'm
not saying something that everybody knows ...)).

On another subject, the 9876543210L constant, the Lattice C compiler
accepts it without flinching. However, such a constant has a real value of
2147483647 (0x7fffffff) (as shown by a printf) which shows that the
compiler detected the overflow condition, but didn't signal it !
(Otherwise, the value would have probably been 1286608618 ...).

David Gay                                   GAY@CLSEPF51.bitnet

I disclaim all responsability for the absence of a disclaimer.

g-rh@cca.CCA.COM (Richard Harter) (03/10/88)

In article <12206@brl-adm.ARPA> GAY%CLSEPF51.BITNET@CUNYVM.CUNY.EDU writes:

	... basically saying to use a struct to hold the return values.

Yeah, sometimes this is exactly what you want to do.  There are a couple
of catches.  The first is that the returned values may not naturally go
into a structure in the calling program.  The second is that you now have
to communicate the declaration of the structure between the two routines;
okay, sortof, if they are in the same file, not so okay if they are in
different files.  Since all good little programmers avoid replicating
declarations like the plague, you put the temporary structure definition
in an include file.  In a large program you end up with a lot of these
yucky little include files, or clump them in a big include file with all
that says about data coupling.  As a practical matter, in C as it stands,
my experience says that it's better to bite the bullet and pass pointers,
doing call by reference by hand -- the code maintenance problems are less.
-- 

In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
	Richard Harter, SMDS  Inc.