The static when used with a function definition indicates that the function has a file level scope. This means that the function name is displayed only inside the file itself. The static used in the definition of a function changes the visibility of the function name and does not change the type of the returned function.
Thus, a function declared static can return some type.
Using static for a variable defined in the function body is used to indicate that the variable should be created at the time the application loads and starts. Therefore, if you use the static modifier for a variable inside a function, this variable is not created on the stack when the function is called. It exists regardless of when the function is called. However, variable visibility is only inside the function.
In your example, you have a function that returns the address of a static variable. You can do this, however, you must understand that this use is not thread safe. In other words, all threads calling the function will receive the same variable in the same memory location, and not in their own version of the variable.
You should also understand that if you return the address of a static variable, you can also cause problems with reraction and recursion. The reason is that the variables on the stack provide reinclusion and recursion, because every time a function is called, a new frame is added to the stack, so each function call has its own stack stack, therefore its own set of variables.
This is a known issue with the old strtok() in the C standard library, which used a variable in strtok() to maintain state between calls, using NULL as the string address, where the last call to strtok() parsed. I saw a problem when a function called strtok() started parsing a string and then called another function, which in turn was called strtok() , to start parsing another string. The result was some really strange errors and behavior until the cause was clarified.
Using the static modifier for a global variable in a file will create a global variable that can be used by several functions within the file. However, like using the static modifier of the function name, the static variable will have the visibility of the file's scope.
Richard Chambers
source share