pure functions are tricky

Brian Westley merlyn at ernie.Rosemount.COM
Mon Feb 20 13:53:20 AEST 1989


It's starting to look like pure functions are like noalias; everyone
knows what it "means" until you look at it more closely.

Simple repeat calls should be optimizable:
	y = sin(x) * sin(x) ;
	z = 1.0 / sin(x++) ;	/* remember to preserve calling side effect */

It should be possible (and legal) to optimize-out the call completely:
	a = b ;
	...
	x = fudge + (sin(a) - sin(b))/100 ;

Now, should it be possible to fold pure functions with constant arguments?
	x = sin(sqrt(2.0)) ;	/* turns into simple assignment to a constant? */

This seems reasonable and desirable, but what about user defined functions?
What about pure functions that can only be evaluated at run time, such as a
function that returns the name of the machine the program is running on?
Can the compiler determine that one pure function can be evaluated completely
at compile-time, and another cannot?  Or should only the former be considered
"pure"?  What about functions that have a first-time-through flag that, e.g.,
precomputes a table of factorials?  Does this destroy its purity?

Somewhat related, is this a legal optimization?

static int sqrs[10];
main()
{
	int i;

	for (i=0; i<10; i++)
		sqrs[i] = i * i;	/* no further assignments to sqrs[] */
	...

static int sqrs[10] = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };
main()
{
	int i;
	...

-----
Merlyn LeRoy



More information about the Comp.lang.c mailing list