scope.c

/*
 * SCOPE -- program to demonstrate how scope works in C
 * 		it does nothing else
 *
 * Usage: scope
 *
 * Inputs: none
 * Output: printing showing value of variable at various points
 * 		in the program
 * Exit Code: EXIT_SUCCESS (0) because all goes well
 *
 * written for ECS 036A
 *
 * Matt Bishop, Oct. 14, 2015
 *	original program written
 * Matt Bishop, Apr. 14, 2023
 *	modified slightly to be cleaner
 */
#include <stdio.h>
#include <stdlib.h>

/*
 * forward declarations (prototypes)
 */
void g(int);
void h(void);

/* the top-level definition */
int variable = 1;

/*
 * the main routine
 */
int main(void)
{
	/* scope is function main */
	int variable = 2;
	printf("main(%d):variable = %d\n", __LINE__, variable);
	/* now an inner block */
	{
		/* scope is the rest of this block */
		int variable = 3;
		printf("main(%d):variable = %d\n", __LINE__, variable);
		/* now an even more inner block */
		{
			/* scope is this block */
			extern int variable;
			printf("main(%d):variable = %d\n", __LINE__, variable);
		}
		/* end innermost block */
		printf("main(%d):variable = %d\n", __LINE__, variable);
	}
	/* end inner block -- back to main block */
	printf("main(%d):variable = %d\n", __LINE__, variable);
	/* now let's show how functions interact with scope */
	g(variable);
	/* bye! */
	return(EXIT_SUCCESS);
}

/*
 * now notice "variable" is a parameter
 * so it (effectively) overrides references to the
 * top-level variable)
 */
void g(int variable)
{
	printf("g(%d):variable = %d\n", __LINE__, variable);
	/* now let's call another function */
	h();
}

/*
 * this function has no declarations, so
 * let's see what it prints
 */
void h(void)
{
	printf("h(%d):variable = %d\n", __LINE__, variable);
}


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