
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Local Static Variables in C Language
A local static variable is a variable, whose lifetime doesn't end with the function call in which it is declared. It extends until the entire programs lifetime. All function calls share the same copy of local static variables.
Static Variables
A static variable preserves its value across multiple function calls, maintaining its previous value within the scope where it was initialized.
These variables are used to count the number of times a function is called. The default value of a static variable is 0. In contrast, normal local scope means that the variables defined within the block are only visible within that block and are not accessible outside of it.
Global Variables
Global variables declared outside a block remain visible and accessible until the end of the program. A global variable in C is defined outside all functions and is accessible throughout the program. It has a scope that includes the main() function. Global variables cannot be defined inside or after the main() function.
Example: 1
This C program specifies two integers, x and y, with values 30 and 40. It then calculates the sum and prints the result by using printf. The output will be 70.
#include <stdio.h> void main() { int x = 30, y = 40, sum; // local variables life is within the block printf("sum=%d", x + y); }
When the above program is executed, it produces the following output ?
sum=70
Example: 2
This C program prints the values of x and z. z is global, accessible in main() and fun(), while a is local.
#include <stdio.h> // Include the standard input-output library int z = 30; // Global variable void fun(); // Function prototype for fun() int main() { int x = 10; // Local variable printf("x=%d, z=%d
", x, z); // Print the values of x and z fun(); // Call the function fun return 0; // Return 0 to indicate successful execution } void fun() { printf("z=%d
", z); // Print the value of the global variable z }
We will get the output as follows ?
x =10, z = 30
Example: 3
In the example below, we define a function fun() with a static variable x initialized to 0. The main() function calls fun() twice, but the code contains errors.
#include <stdio.h> // Include the standard input-output library void fun(); // Function prototype for fun() int main() { fun(); // Call the function fun fun(); // Call the function fun again return 0; // Return 0 to indicate successful execution } void fun() { static int x = 0; // Static variable initialized to 0 printf("%d ", x); // Print the value of x x = x + 1; // Increment the value of x }
The result is generated as follows ?
0 1