5

C99 has added static in a function parameter (only meaningful in the function definition, not declaration):

void func( int a[static 10] )
{
    if ( a == NULL )
       { /* this branch can be optimized out */ }

    printf("%d", a[-1]);    /* causes UB */
}

However, its meaning is defined in C11 6.7.6.3/7 as a semantic, not a constraint, which means that the compiler should not issue a diagnostic if the function is called incorrectly. In fact the compiler must not abort compilation unless it can prove that UB is caused in all branches. For example:

int main()
{
    func(NULL);   // UB

    int b[9];
    func(b);      // UB
}

Why did the Standard not make this a constraint (therefore requiring a diagnostic)?

Secondary question: why is static ignored in the prototype (6.7.6.3/13), instead of being a part of the function signature? It seems misleading to allow the prototype to contain it but the function body doesn't, and vice versa.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    `int *p = create_array(); func(p);` How do you diagnose this? – T.C. Mar 17 '15 at 03:22
  • 2
    As to q2, the `static` in the array declarator is not a storage-class specifier, therefore 6.7.6.3/13 doesn't apply. Cf. 6.7.6.3/2 - "The only storage-class specifier that shall occur in a parameter declaration is `register`." – T.C. Mar 17 '15 at 03:23
  • @TC re. q2: OK, so does that mean it is actually significant in the prototype? – M.M Mar 17 '15 at 03:31

1 Answers1

5

Because violations cannot be detected at compile time in all cases.

For example, the argument could be a pointer to the initial element of an array allocated with malloc(). The compiler cannot in general determine how big the array is. Nor, if the argument is a pointer object, can the compiler detect in general whether it's null.

The main purpose of this feature is not to enforce restrictions on calls, but to enable optimizations. The compiler may assume that the parameter points to the initial element of an array of the specified length. In some cases, this can enable better code generation.

But compilers certainly can issue non-fatal warnings for the cases they can detect. There is no implication in the standard that such warnings should not be issued.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Just discovered that clang 4.1 [does issue warnings](http://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html) for some simple cases – M.M Mar 21 '15 at 08:50