Why is [static N] not applied at compile time?

C99 added static to the function parameter (only the value in the function definition, not the declaration):

void func( int a[static 10] ) { if ( a == NULL ) { /* this branch can be optimized out */ } printf("%d", a[-1]); /* causes UB */ } 

However, its value is defined in C11 6.7.6.3/7 as semantic and not a limitation, which means that the compiler should not issue diagnostics if the function is called incorrectly. In fact, the compiler should not interrupt compilation if it cannot prove that UB is called in all branches. For instance:

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

Why did the standard not make this restriction (therefore requires diagnostics)?

Secondary question: why is static ignored in the prototype (6.7.6.3/13) instead of being part of the function signature? It seems to be misleading that the prototype contains it, but the body of the function does not, and vice versa.

+5
source share
1 answer

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

For example, the argument may be a pointer to the source element of an array allocated using malloc() . The compiler cannot determine at all how large the array is. Also, if the argument is a pointer object, can the compiler even determine if it is null?

The main purpose of this function is not to apply call restrictions, but to enable optimization. The compiler may assume that this parameter points to the starting element of an array of the specified length. In some cases, this may provide better code generation.

But compilers can certainly give non-fatal warnings for cases that they can detect. The standard does not imply that such warnings should not be issued.

+5
source

Source: https://habr.com/ru/post/1215493/


All Articles