How to Make Static Variables in C Programming

By Dan Gookin

In C programming, variables used within a function are local to that function: Their values are used and then discarded when the function is done. Don’t Give Me No Static demonstrates the concept.

DON’T GIVE ME NO STATIC

#include <stdio.h>
void proc(void);
int main()
{
 puts("First call");
 proc();
 puts("Second call");
 proc();
 return(0);
}
void proc(void)
{
 int a;
 printf("The value of variable a is %dn",a);
 printf("Enter a new value: ");
 scanf("%d",&a);
}

In Don’t Give Me No Static, variable a in the proc() function does not retain its value. The variable is initialized only by the scanf() function at Line 20. Otherwise, the variable contains junk information.

USING TYPEDEF TO DEFINE A STRUCTURE

typedef struct id
{
 char first[20];
 char last[20];
} personal;
typedef struct date
{
 int month;
 int day;
 int year;
} calendar;
struct human
{
 personal name;
 calendar birthday;
};

Exercise 1: Build and run a new project using the source code from Using typedef to Define a Structure.

he output looks like this:

First call
The value of variable a is 0
Enter a new value: 6
Second call
The value of variable a is 0
Enter a new value: 6

Despite all attempts to assign 6 to variable a, the program always forgets. So much for that. Or is it?

Exercise 2: Modify the source code from Using typedef to Define a Structure, editing Line 16 to read:

static int a;

Build and run to test the output.

First call
The value of variable a is 0
Enter a new value: 6
Second call
The value of variable a is 6
Enter a new value: 5

Because the variable was declared as static, its value is retained between function calls.

  • You have no need to declare variables as static unless you need their values retained every time the function is called, and this situation crops up from time to time. But before believing it to be a magic cure, also consider creating global variables.

  • Variables returned from a function do not need to be declared static. When you return a variable, such as

    return(a);

    only the variable’s value is returned, not the variable itself.