/***************************************************************************
* Columbia University Introduction to Computer Programming in C COMS 1003
* Example use of the static keyword for local variables
*
* Copyright (C) 2005 Michael E. Locasto
*
* All rights reserved.
*
* $Id: statictest.c,v 1.1 2005/10/08 19:17:51 locasto Exp $
**************************************************************************/
#include
/* Demonstrate the use of a C preprocessor define statement to symbolically
* equate the string of characters 'MAX_GRADES' with the string of
* characters '20'
* Note that this statement is NOT a C statement and thus does not end in
* a semi-colon.
*/
#define MAX_GRADES 20
/* Global Variables */
int grades[MAX_GRADES]={0};
/* Function declarations */
int add(int);
//------------------------------------------- function implementations
/*
* A lame add function that is contorted into serving as an
* example of the use of the 'static' keyword to keep around
* the value of a local variable between invocations of a
* function. An alternative implementation of this function would
* receive another parameter (say, 'i') that indicates which value in
* the grade array should increment the grade sum. That function would
* then be invoked in the for() loop in main() via:
* sum = add(sum, i);
*/
int add(int sum)
{
/*
* Declare and initialize the local variable 'where'
* It is initialized only once: the first time control
* flow enters the function.
*/
static int where = 0;
/*
* A non-static local variable that doesn't help the program in
* any way except to show that non-static local variables have
* their value wiped out between function calls.
*/
int somewhere = 0;
int sum_result = 0;
sum_result = sum+grades[where];
/* Update the value of where */
where++;
/*
* Prove to the skeptics that where maintains its value between
* invocations.
*/
printf("where == %d\n", where);
/* Update the value of 'somewhere' */
somewhere++;
/*
* Show that 'somewhere' does not maintain its value between
* invocations of this function, so it always starts off at
* zero and is incremented to 1, then is recycled when the
* function returns.
*/
printf("somewhere == %d\n", somewhere);
/* Send data back to our caller. */
return sum_result;
}
/**
* Demonstrate the use of the static keyword and a global
* variable 'grades': an array of integers.
*
*
*/
int main(int argc, char* argv[])
{
int i = 0;
int sum = 0;
float avg = 0;
/* We assume (for simplicity) that the grades array actually has
* these positions.
*/
grades[0] = 30;
grades[1] = 100;
grades[2] = 80;
grades[3] = 90;
for(i=0;i0)
{
avg = ((float)sum)/(MAX_GRADES);
printf("The average grade is: %3.1f\n",avg);
}else{
printf("There were no grades to calculate an average.\n");
}
return 0;
}