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; }
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.
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 in c global? No. For one thing, what many call (sloppily) global, the C Language calls file scope with external linkage.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With