Wednesday, 17 February 2016

Importance of static variables in C

In this post I am going to tell you about why you need to declare the local variables of a function as a static?
In the below example there are two functions getBuckets(uint32_t key, struct Table *td) and lookup(uint32_t key, struct Table *td). The lookup() function internally calls the getBuckets() function. The getBuckets() function returns an array of integers, which can be then accessed by the bucketList variable of a lookup() function.
If I did not declare the bucketID variable as a static then soon after the execution of the getBuckets() function the stack will flush out and all the local variables will be reinitialized. So I declared it as a static variable so that the system will allocate memory separately not on the stack. So you can still excess values  of that particular variable out side from that particular function.

No comments:

Post a Comment