Static Variables and Functions in C

Filed Under: C Programming
C Static Variables And Functions

Static Variables in C

Basically, when static variables are declared, they create only a single copy of them and are also termed as Class Variables.

They retain the value assigned in the corresponding scope and do not initialize the variables again in the new scope of it.

  • Static variables remain in the memory space during the execution of the code.
  • The default value of the initialization of the Static variable is zero (0).
  • In C programming, it is mandatory for the static variables to be initialized using the constant literal else it returns an error.

Syntax:

static Data_Type variable = value; 

Example:

#include<stdio.h> 
void implement() 
{ int x = 0;
static int counter = 0; 
counter++; 
x++;
printf("\nStatic Variable's value:\n");
printf("%d",counter);
printf("\nLocal Variable's value:\n");
printf("%d",x);
} 

int main() 
{ 
implement();
implement();
return 0; 
}

In the above code snippet, the value of the local variable gets initialized again after every function call.

Unlike the local variable (x), the static variable (counter) was initialized only once and it did retain the same copy of variable throughout the execution of the program.

Output:

Static Variable's value:
1
Local Variable's value:
1
Static Variable's value:
2
Local Variable's value:
1

Static Functions in C

Static functions in C basically restrict the scope of the method to the corresponding file. These functions can also be called without having the object initialized.

  • Static functions usually enhance the usability of the code i.e. makes the code ready to be reused again.
  • It limits the visibility of the scope of the function within that particular program.

Syntax:

static Return_Type method_name(parameters)
{
    body;
}

Example:

#include <stdio.h>

//static function definition
static int sum(int a, int b){
	return (a+b);
}

int main()
{
	int number1,number2;;
	printf("Enter the number1: ");
	scanf("%d",&number1);
	printf("Enter the number2: ");
	scanf("%d",&number2);
	printf("Addition of two numbers = ");
	int res = sum(number1,number2);
	printf("%d",res);
	return 0;
}

Output:

Enter the number1: 10
Enter the number2: 20
Addition of two numbers = 30

Conclusion

Thus, in this article, we have understood the importance and behavior of static variables and static functions in the C programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages