Home » C programming language

Static functions in C Language



As we know that the functions defined in a file can be accessed in another file. If we want to restrict that functions must not be called in another file, we can make them static.

Hence, static functions are those functions which are callable in the same file where they define.

We can define a function static by using following syntax

static return_type function_name(arguments)
{
    function_body;
}

Here is a function to find square root of a given number

static long int getSquare(int num){
	return (num*num);
}

Consider the following program

Program to demonstrate example of static function in C language

#include <stdio.h>

//static function definition
static long int getSquare(int num){
	return (num*num);
}

int main()
{
	int num;
	printf("Enter an integer number: ");
	scanf("%d",&num);
	printf("Square of %d is %ld.\n",num,getSquare(num));
	
	return 0;
}

Output

    Enter an integer number: 36 
    Square of 36 is 1296.

Why the static functions are required?

Since functions are used to reuse the code (i.e. the code that you have written can access in another file by putting them in the functions), but when you want to define some functions that should not be sharable (callable) in another file.

static functions are also helpful to handle declaration conflict issue - if there are two functions in two different files with same name, function declaration will be conflict. We can make them static.

To fulfil such kind of requirement, we can make them static.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.