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.
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
#include <stdio.h>
void visit(void)
{
static int count = 0;
count++;
printf("Visit %d\n", count);
}
int main(void)
{
visit();
visit();
visit();
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Visit 1 Visit 2 Visit 3
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Initialize a static local variable once and observe that its value survives later function calls.
- 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.
