Answers to questions on static variables in functions

  1. Write a function which has a single integer parameter and uses static integer variables to keep track of the mean of all values passed to it during the running of a program. It should return the mean so far each time it is called. Test it in a program.
    float mean_so_far(int val)
    {
       static int sum, number; /*Statics are set to zero initially*/
       sum = sum + val;
       number++;
       return sum / number;
    }
    

  2. Why can this function only keep a running mean for one stream of values?
    Because there is only one instance of each of the stsic variables. It would be necessary to define a different version of the function, with a unique name, for each stream to be recorded. This weakness was one of the reasons for the extension into the use of objects.

Back to the questions.


Back to notes on statics in functions.