What is use of static function in C language programming?

(Last Updated On: February 25, 2019)

Answer includes the use of static function in c language programming with explanation and C code example. You can read static function definition with example that  is asked in a technical interview .

Answer:

For below reasons we should use static function in C program.

  • Limit the scope/visibility of a function in a C programs.
  • Reuse of the same function name in other C source files

Let’s explain both above uses with a program example in C.

1)Limit the scope / visibility of a function in a C program.

In a C source file, generally, we have internal and public APIs and we make the visibility of public APIs only to client (e.g. main()). So, in C programming , we use static functions to restrict the access of internal APIs to client.

As an example, let’s have a music.h header file that contains declaration of two functions “static void buffer()” as an internal function for buffering music and PlayMusic() as a public functions . in music.c we will define these functions.

In the below C program, only PlayMusic() function will be accessible to main.c source file and buffer() function to file itself i.e. music.c only and not to main.c as it is a static function.

//music.h //header file

 

//music.c //source file

//Client – main.c

Output:
Buffering Music…
Play Music

 

 

2)Reuse of the same function name in other source files

In C language programming , static function is also used to avoid ambiguity. If we have the same function name in different source files in an application.

For example, in above program lets include one more file “video.h” and “video.c” that have function with same name i.e. void buffer() as we have in music.h.

//Video.h – header file

//video.c – source file

 

In files music.h and video.h if the buffer() function is not static we’ll get compiler error in following program as compiler will find buffer in music.h first and then it goes to video.h and find the same and complain that buffer() is already defined in music.h.

 

 

So, Once we make buffer() function as static no conflict will occur, hence function name can be reused in a same program.

Static function – Complete C Program Example:
//music.h

//music.c

//video.h

 

//main.c