Functions - C Interview Questions III


Q. What is a static function?
A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.
A static function therefore can be seen and used only by other functions within the current source file. When you have a function that you know will not be used outside of the current source file or if you have a function that you do not want being used outside of the current source file, you should declare it as static. Declaring local functions as static is considered good programming practice. You should use static functions often to avoid possible conflicts with external functions that might have the same name.
For instance, consider the following example program, which contains two functions. The first function, open_customer_table(), is a global function that can be called by any module. The second function, open_customer_indexes(), is a local function that will never be called by another module. This is because you can't have the customer's index files open without first having the customer table open. Here is the code:
#include <stdio.h>
int open_customer_table(void);       /* global function, callable from
                                        any module */
static int open_customer_indexes(void); /* local function, used only in
                                           this module */
int open_customer_table(void)
{
     int ret_code;
     /* open the customer table */
     ...
     if (ret_code == OK)
     {
          ret_code = open_customer_indexes();
     }
     return ret_code;
}
static int open_customer_indexes(void)
{
     int ret_code;
     /* open the index files used for this table */
     ...
     return ret_code;
}
Generally, if the function you are writing will not be used outside of the current source file, you should declare it as static.

Comments