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.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.