macros.c

/*
 * this demonstrated the use of the C preprocessor macro #define
 *
 * Matt Bishop, ECS 36A
 *
 * April 22, 2024
 *	first version
 */
#include <stdio.h>

/*
 * macros
 */
/* a number */
#define	NINE	9
/* side of a chessboard, with border rows and columns -- BAD */
#define SIDE	8+2
/* the above done right -- GOOD */
#define SIDE1	(8+2)
/* common problem: expression that dupliocates a parameter      */
/* and is passed an expression changing the value of a variable */
#define isbetween0and9(x)	((0 <= (x)) && ((x) <= 9))

/*
 * the program
 */
int main(void)
{
	int x;		/* used to show side effect in a macro */

	/* show sides, including surrounding row and column */
	printf("bad side = %d, good side = %d\n", SIDE, SIDE1);

	/* print number of squares in a chessboard two ways */
	printf("chessboard with bad side has %d squares (wrong!)\n",
								SIDE * SIDE);
	printf("chessboard with good side has %d squares (right!)\n",
								SIDE1 * SIDE1);


	/* now set x for the side effect demo */
	x = NINE;

	/* no side effect -- this is true, so print first printf */
	if (isbetween0and9(x))
		printf("%d is between 0 and 9\n", x);
	else
		printf("%d is not between 0 and 9\n", x);
	/* now side effect -- this is false, as (0 <= (x)) is true but */
	/* now x i 10, so ((x) <= 9) is false; x incremeneted to 11    */
	if (isbetween0and9(x++))
		printf("%d is between 0 and 9\n", x);
	else
		printf("%d is not between 0 and 9\n", x);
		
	/* ta-ta for now */
	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