[net.lang.c++] inline functions

bs@alice.UucP (Bjarne Stroustrup) (03/10/86)

> Path: alice!allegra!ulysses!ucbvax!cad!rudell
> From: rudell@cad.UUCP (Richard Rudell)
> Newsgroups: net.lang.c++
> Subject: Question about 'inline' functions
> Organization: U. C. Berkeley CAD Group
> 
> Consider the following c++ program:
> 
> 	#include <stream.h>
> 	#include <complex.h>
> 
> 	main()
> 	{
	    ...
> 	    complex e = (a + b) + (c + d);
> 	}
> 
> The '+' overload for type complex is:
> 
> 	friend	complex	operator+(complex, complex);
> 			...
> 	inline complex operator+(complex a1, complex a2) 
> 	{
> 		return complex(a1.re+a2.re, a1.im+a2.im);
> 	}
> 
> By examining the output of cfront for the above program, I find that only
> 1 of the three '+' operators is actually expanded inline.  A dummy
> function is created which performs the addition operation, and then this
> function is called twice to handle the final two additions.

> My questions are: 
>     Why isn't the entire expression placed "inline" ?
> and: 
>     Is this a temporary limitation, or a necessary (and hence
>     permanent) limitation of c++ ?

It is a ``temporary limitation''. Cfront will expand an inline function at
most once in a single expression and if/when it sees a second call it will
``outline'' the function and call it for the second and subsequent calls
in that expression (only). 

This ``limitation'' was introduced to make inline expansion simpler.
It allowed me to use fewer temporaries and have their names correspond
more directly to the names used by the programmer. There is no fundamental
reason for it, and one might argue that the ``simplification'' of the compiler
never really happened/payed-off. I don't expect the limitation to be permanent.

Where efficiency really matters you could circumvent the ``outlining'' at the
cost of some loss of clarity and of a few copy operations:

	complex e = a;	// complex e = (a + b) + (c + d);
	e += b;
	e += c;
	e += d;		// not pretty, but no function calls

	- Bjarne Stroustrup (AT&T Bell Labs, Murray Hill)

Note also that overloaded op= functions can be a real boon since they alliviate
the need for temporary variables.