Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static hint in variable length arrays

Tags:

arrays

c

c99

I'm a bit confused at the difference here, in C99:

int myfunc (int array[n], int n) { ... }

will not compile. As far as I know you must always put the reference to the array size first, so it has to be written:

int myfunc (int n, int array[n]) { ... }

But if you supply the static keyword, this works absolutely fine:

int myfunc (int array[static 1], int n) { ... }

This order if far preferable to me, as I'm used to having arrays come first in a function call, but why is this possible?

Edit: Realising that the third example isn't actually a VLA helps...

For reference, this was the piece of code I was looking at that led to the question:

int sum_array(int n, int m, int a[n][m])
{
  int i, j, sum = 0;
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++)
      sum += a[i][j];
  return sum;
}
like image 678
teppic Avatar asked Dec 21 '22 16:12

teppic


1 Answers

The reason why

int myfunc (int n, int array[n]) { ... }

is valid and

int myfunc (int array[n], int n) { ... }

is not is due to the lexical scoping rules of C. An identifier cannot be used before it has been introduced in the scope. There are a few exceptions to this rule but this one is not one of them.

EDIT: here is the relevant paragraph of the C Standard:

(C99, 6.2.1p7) "Any other identifier has scope that begins just after the completion of its declarator."

This rule also applies to parameters declaration at function prototype scope.

like image 96
ouah Avatar answered Dec 24 '22 01:12

ouah