C99 allows array parameter sizes to be static
:
#include <stdio.h>
int sum(const int v[static 10])
{
int s = 0;
for (int i = 0; i < 10; i++)
s += v[i];
return s;
}
int main(void)
{
int v[4] = { 1, 2, 3, 4 };
printf("%d", sum(v));
}
From what I understand, the compiler should throw an error when calling sum()
, because I need to pass an array of at least 10 elements. The compiler, however, seems to ignore the static
keyword and proceeds with passing an array of 4 elements. Of course, since the function uses 10 elements, it is undefined behavior (and the output is some random non-sense made of what is beyond the array). What is the problem?