Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the advantage of static function?

Tags:

c

static

see in one project source code i have seen belows declaration

static int *foo();

so it declare foo as static function returning pointer to int. So here i wana ask you whats the purpose of declaring function as static ?

like image 248
Jeegar Patel Avatar asked Oct 18 '11 20:10

Jeegar Patel


People also ask

What are the advantages of static method?

A static method belongs to the class rather than the object of a class. A static method can be invoked without the need for creating an instance of a class. A static method can access static data member and can change the value of it.

What is the advantage of static function in C++?

Static function: Advantage: it could be called without existing real object. Static member functions become useful when you want the class as a whole to have a function, instead of each individual object. With a static member function, you can then change static variable data.

What is the purpose of static function?

Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.


2 Answers

It prevents other translation units (.c files) from seeing the function. Keeps things clean and tidy. A function without static is extern by default (is visible to other modules).

like image 96
cnicutar Avatar answered Sep 23 '22 03:09

cnicutar


Declaring a function as static prevents other files from accessing it. In other words, it is only visible to the file it was declared in; a "local" function.

You could also relate static (function declaration keyword, not variable) in C as private in object-oriented languages.

See here for an example.

like image 42
Evan Mulawski Avatar answered Sep 25 '22 03:09

Evan Mulawski