johni
johni

Reputation: 5568

declare array once C

If I have a function that is called A LOT of times, and that function needs an array of 16 pointers that will be updated with new pointers every time it's called, is this the right way to declare this array?

char** readUserInput() {
    static char* cmds[16];
    ...

}

Will this array be initialized once?

Upvotes: 1

Views: 122

Answers (4)

user3125367
user3125367

Reputation: 3000

It is unclear whether you have to return that array from hot function. If yes, it has to be static or has to be passed as an argument. Even if not, then there is no difference in "speed" between static and auto-array, because your reuse scheme should anyway have means of [possibly no-op] preinitialization before call, and no matter what very first initial value was.

Drawback of static storage is that code becomes non-reentrant. Passing it as an argument would be more correct solution.

Upvotes: 2

Benjy Kessler
Benjy Kessler

Reputation: 7616

Yes, static variables are only initialized once. By declaring the variable cmds you are declaring an array of 16 char*s. The array is initialized with zeroes. The array will never be initialized again.

Take this code as an example:

int i;
static char *cmds[5];
for (i = 0;i<5;++i) {
  printf("%d ", cmds[i]);
}

It prints:

0 0 0 0 0

Upvotes: 4

anon
anon

Reputation:

Static variables are only initialized/declared once and the static keyword is useful to provide a lifetime over the entire program, but limit their scope.

Upvotes: 2

WhozCraig
WhozCraig

Reputation: 66194

It is declared only once regardless of whether it houses the static storage specifier. Don't confuse declare with lifetime.

If the real question is "will there be only one instance of cmds, and will its content persist between calls?", then yes. It is declared with the static storage class specifier. Per §6.2.4.3 of the C11 standard

... Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup."

Upvotes: 3

Related Questions