06-22-2006 07:59 AM
Solved! Go to Solution.
06-22-2006 08:33 AM
06-22-2006 09:05 AM - edited 06-22-2006 09:05 AM
Message Edited by mvr on 06-22-2006 09:08 AM
06-22-2006 10:53 AM
06-22-2006 11:54 AM
This explanation of the static keyword is mostly correct. However, the static keyword serves another function and the semantics of its usage is dependent on variable scope.
If the variable is defined as static outside of a function, it behaves as Mert describes.
If it is used within a function, the static keyword indicates to the compiler that the variable is to be allocated on the heap and maintained between function calls as opposed to the normal dynamic allocation of variables on the stack.
There are a number of reasons for choosing one storage class over the other, one of them being stack space limitations. If you define a number of large buffers in a function, it might be better to do so using the static keyword to prevent potential stack overflow. On the other hand, if you are using a function recursively, it will not allocate new variables when using the static keyword making any access to those variables problematic in such a recursive state.
The way to solve the recursion problem is to use malloc (and its variations) to dynamically allocate a buffer in a function. The only problem with this is you need to free the memory before exiting your function to prevent memory leaks.
Isn't programming fun? :