UMBC CS 201, Fall 06
 UMBC CMSC 201 Fall '06 CSEE | 201 | 201 F'06 | lectures | news | help Search Notes:

# local

## The Program

/********************************************** ** File: local.c ** Author: R. Chang ** Date: ?/?/199? ** Section: 101 ** EMail: chang@gl.umbc.edu ** ** A program to demonstrate local variables. ** and the concept of a variable's "scope" **********************************************/ #include <stdio.h> /* Function Prototypes */ void RedFish (int i); void BlueFish (int n); int main () { int n; n = 17; /* Illustrates calling a function passing a constant */ printf("Before calling RedFish, n = %d\n", n); RedFish (32); printf("After calling RedFish, n = %d\n", n); printf("\n"); /* Illustrates that the function does not modify main's local variable, n */ printf("Before calling BlueFish, n = %d\n", n); BlueFish (n); printf("After calling BlueFish, n = %d\n", n); return 0; } /***************************************** ** Function: Redfish() ** Usage: Redfish(i) ** ** The function RedFish illustrates the idea of ** local variables and 'scope' ** ** Input: integer i for demo purposes ** Output: None *****************************************/ void RedFish (int i) { int n; i = 2; n = 14; printf(" In RedFish, i = %d, n = %d\n", i, n); return; } /***************************************** ** Function: Bluefish() ** Usage: Bluefish(i) ** ** The function BlueFish illustrates the idea of ** local variables and 'scope' ** ** Input: integer i for demo purposes ** Output: None *****************************************/ void BlueFish (int n) { n = 72 ; printf(" In BlueFish, n = %d\n", n); return ; }

## The Sample Run

Before calling RedFish, n = 17 In RedFish, i = 2, n = 14 After calling RedFish, n = 17 Before calling BlueFish, n = 17 In BlueFish, n = 72 After calling BlueFish, n = 17

## The Lesson

• Changes to a local variable are local to the function. They do not effect variables in the main function or in any other function.
• The code in which a variable may be refereneced is called the variable's "scope". A variable's scope should be as small as possible

CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:13:54 EDT