Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static local function vs global function

Tags:

c++

static

global

What is the utility of having static functions in a file ?

How are they different from having global functions in a file ?

static int Square(int i) {    return i * i; }  

vs

int Square(int i) {    return i * i; } 
like image 326
Arun Avatar asked Feb 07 '13 02:02

Arun


People also ask

How are static functions different from global functions in C?

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.

What is the difference between a global function and a local function?

Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function. It is possible to have local variables with the same name in different functions.

Are all functions global in C?

Are all functions in c global? No. For one thing, what many call (sloppily) global, the C Language calls file scope with external linkage.

What is a local function in C?

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example shows how local variables are used.


2 Answers

What is the utility of having static functions in a file?

You can use these functions to provide shared implementation logic to other functions within the same file. Various helper functions specific to a file are good candidates to be declared file-static.

How are they different from having global functions in a file?

They are invisible to the linker, allowing other compilation units to define functions with the same signature. Using namespaces alleviates this problem to a large degree, but file-static functions predate namespaces, because they are a feature inherited from the C programming language.

like image 154
Sergey Kalinichenko Avatar answered Sep 22 '22 09:09

Sergey Kalinichenko


A static function simply means that the linker cannot export the function (i.e. make it visible to other translation units). It makes the function "private" to the current translation unit. It is the same as wrapping the function in an anonymous namespace.

namespace {      int Square(int i)     {        return i * i;     }   } 

Generally, using an anonymous namespace is the preferred C++ way of achieving this, instead of using the static keyword.

like image 37
Charles Salvia Avatar answered Sep 20 '22 09:09

Charles Salvia