Explain static function in C language with example

Answer: Static function in C language with example. In C language programming, static function is a function whose scope (visibility) is limited to the current source file. Means, the function will be visible to only the source file in which it is defined and cannot be accessed outside of this file.

We use the static keyword before function in C to declare a function as a static function. For example

static void buffer();

As an example, consider a header file A.h, where we have declaration a static function and A.c a source file in which static function is defined.

//A.h – header file

static void func();

//A.c – source file

void func(){

//static function definition

}

As per definition,static function is only available to A.c source file and not accessible outside it.means, no any other source files.

If we try to access static function in other source files for example in main.c, compiler will flash an error i.e. func() declared but not defined.

If function is not static, below call will be ok.

//main.c

#include "A.h"

int main(){

func();//Compiler error : void func() declared but not defined.

return 0;

}

NOTES:

We use static functions in C programming for below reasons.

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

Related Posts