C PROGRAMMING PROGRAM • FUNCTIONS, PREPROCESSOR & COMMAND LINE

Preserve Function State with a static Local Variable

Learn how to preserve function state with a static local variable using a clear C program.

Beginnerstatic localStorage durationFunction calls

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Visit 1
Visit 2
Visit 3

COMPLETE C PROGRAM

Complete C implementation

static-local-counter.c
Open in compiler
#include <stdio.h>

void visit(void)
{
    static int count = 0;
    count++;
    printf("Visit %d\n", count);
}

int main(void)
{
    visit();
    visit();
    visit();
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Visit 1
Visit 2
Visit 3
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Initialize a static local variable once and observe that its value survives later function calls.
  3. Display the computed result.

Initialize a static local variable once and observe that its value survives later function calls.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.