fptr.c

/*
 * simple prograam showing how function pointers work
 *
 * Matt Bishop, ECS 36A
 * -- May 22, 2024	original program
 */
#include <stdio.h>

/* add 4 to argument and return result */
int add(int x)
{
	return(x + 4);
}

/* subtract 4 to argument and return result */
int sub(int x)
{
	return(x - 4);
}


/*
 * main program
 */
int main(void)
{
	int (*f)(int);		/* functiomn pointer variable */

	/* first we add and then print the result */
	f = add;
	printf("%d + 4 = %d\n", 5, f(5));

	/* next we subtract and then print the result */
	f = sub;
	printf("%d - 4 = %d\n", 5, f(5));

	/* all done! */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh