by Dinesh Thakur Category: Array

This feature can be used with arrays as well. A static array has the following characteristics:

1. It has a local scope. Thus, it can be used only within the block in which it is defined.

2. It is initialized only once, the first time the control passes through its declaration.

3. If a static array is not explicitly initialized, its elements are initialized with the default value which is zero for arithmetic types (int, float, char) and NULL for pointers.

4. A static array has a lifetime till the end of program execution. Thus, a static array defined within a function is not destroyed when control leaves that function and the value of this array is available the next time the function is called.

For example, we used the month_days function to determine the maximum number of days in a given month. This function uses an array mdays to store the number of days in each month. Note that this function is quite inefficient as mdays array will be initialized each time the function is called. We can overcome this problem by declaring mdays as a static array, as shown below.

/* determine maximum number of days in given month */

int month_days(int m, int y)

static int mdays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} ;

return mdays[m] + (m == 2 && is_leap(y) ? 1 : 0);

Now mdays array is initialized only once, the first time this function is called. This array is preserved for use in subsequent executions of this function. Thus, program execution will speed up now, of course at the cost of memory used by this array. Further, we can declare this array as a const array to avoid any inadvertent changes being made to it.

static const int mdays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles