switch.c

/*
 * show a version of the if program using a switch
 # you can set x to 9, 10, 11, 12 by defining X9, X10, X11, X12
 * default is x = 10
 * If you want the version that won't compile, set BADVAR
 * If you want the version that "falls through", set NOBREAK
 *
 * Matt Bishop, ECS 36A
 * April 9, 2024	original version
 */
#include <stdio.h>

int main(void)
{
	int x = 10;	/* variable used in the switch */
#ifdef BADVAR
	int y = 9;	/* variable used in the  case -- illegal! */
#endif

	/* now reser the value of x as desired */
#if defined(X9)
	x = 9;
#elif defined(X10)
	x = 10;
#elif defined(X11)
	x = 11;
#elif defined(X12)
	x = 12;
#endif

	/*
	 * now the switch
	 */
	switch(x){
	case 12:
		printf("x is 12!\n");
		break;
	case 11:
		printf("x is 11!\n");
		break;
	case 10:
		printf("x is 10!\n");
#ifdef NOBREAK
		/* FALLS THROUGH */
#else
		break;
#endif
	default:
		printf("I have no clue what x is :(\n");
		break;
#ifdef BADVAR
	case y:
#else
	case 9:
#endif
		printf("x is 9!\n");
		break;
	}

	/* 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