------------------------------------------------------------------------------
MC logo
Static Local Data in C
[^] Chapter Outlines
------------------------------------------------------------------------------
[Ch. 1: Overview and History] [Syntax] [Names and Scope] [Types and Type Systems] [Semantics] [Functions] [Memory Management] [Imperitive Programs and Functional Abstraction] [Modular and Class Abstraction] [Functional Programming] [Logic Programming]
static.c
#include <stdio.h>

/*
 * This example demonstrates a simple use of static data.  It also makes some
 * more advanced use of printf.  The program prints a very simple ledger.  The
 * function print_line keeps a running balance, printing one line each time it
 * is called.  It uses static data to keep track of the total, and to condition
 * the first call to print headers.  The use of static is important, since
 * the value of the first flag and of the balance must persist between calls
 * to print_line.
 */

/*
 * Print table line.  It receives a description and an amount. 
 */
void print_line(char *descr, double amt)
{
        static int first = 1;           /* Identifies first call. */
        static double balance = 0.0;    /* Running balance. */

        /* First time through, print header line. */
        if(first)
        {
                printf("%-20s%10s%10s\n", "Description", "Amount", "Balance");
                printf("%-20s%10s%10.2f\n", "Initial Balance", "", 0.0);

                first = 0;
        }

        /* Now, process the transaction, and print. */
        balance += amt;
        printf("%-20s%10.2f%10.2f\n", descr, amt, balance);
}

/* Just a convenient place to keep pairs of test data arguments for 
   print_line. */
struct legdat
{
        char *descr;
        double amt;
};

/*
 * Just a boring test driver
 */
main()
{
        /* Lists of data to send to the ledger. */
        struct legdat legdat[] = {
                "Paycheck", 1579.17,
                "Gas", -14.56,
                "Rent", -550.16,
                "Refund", 33.45,
                "Pizza Party", -155.18,
                "New Carpet", -250.00,
                NULL };
        struct legdat *scan;

        /* Go through the data and print the lines. */
        for(scan = legdat; scan->descr != NULL; ++scan)
                print_line(scan->descr, scan->amt);
}