Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static in front of number in a c program [duplicate]

Tags:

c

static

So i was reading a blog about optimizing sorting of blocks of an int and the implementation was in c. I came over this line that i do not understand:

void nibble_sort_bucket(uint64_t buf[static 1024]) {

The buffer is basically data to be sorted and each int in it gets its blocks of 4 bit sorted, so it is basically for benchmarking. When i looked up the usage of static in c i found two things.

  1. Keeping function definitions private to a file.
  2. Keeping a variable value between calls of a function.

Neither of these makes sense here. Can someone explain why you would ever write static in front of a number and what that does?

like image 229
Siniyas Avatar asked Jul 31 '15 14:07

Siniyas


2 Answers

That is third meaning of the static keyword, that was introduced in C99, but it is not well known feature. Its purpose is to tell compiler, that you are passing an array with at least 1024 elements.

From C99 (N1256) §6.7.5.3/p7 Function declarators (including prototypes) (emphasis mine):

If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

There is some discrepancy between actual implementations. For instance clang throws an warning, when passed array does not satisfy above subclause. For instance:

#include <stdio.h>

void foo(int a[static 10]) {}

int main()
{
    int array[8] = {0};

    foo(array);
}

gives:

warning: array argument is too small; contains 8 elements, callee requires at least 10 [-Warray-bounds]

while the gcc implementation does nothing (see GCC bug 50584 for more information).

like image 70
Grzegorz Szpetkowski Avatar answered Sep 19 '22 17:09

Grzegorz Szpetkowski


This statement buf[static 1024]tells the compiler that buf is atleast 1024 characters long. It is used for optimization, in other words it wants to say that buf can never be null.

like image 30
Nishant Avatar answered Sep 19 '22 17:09

Nishant