Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

function - What is the meaning of “static” in parameters array types in C?

I saw following little complicated function definition.

void foo(double A[static 10]) {
   double B[10];    
}

Is it valid C & C++ code? Is it new syntax introduced by C99 or C++ standard? What is the purpose of it? When should I use it? What is the need for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This C99 notation, void foo(double A[static 10]), means that the function can assume that A points to 10 valid arguments (from *A to A[9]). The notation makes programs more informative, helping compilers to both optimize the code generated for the function foo and to check that it is called correctly at each call site.

In the C99 standard, in which the notation was introduced, this is covered by clauses 6.7.5.2 and 6.7.5.3:7.

“… 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”


One common use is f(int p[static 1]), which is more or less equivalent to the notion of reference (as opposed to pointer) in other languages. Clang warns if such a function was declared and is passed a null pointer at the call site (because the notation explicitly means that p will not be NULL). However, the last time I tried, Clang did not warn for f(&a + 1), which is a shame (but a compiler doesn't have to emit all warnings. Emitting some warnings is good already):

#include <stdio.h>

void f(int p[static 1])
{
  printf("%d
", *p);
}

int main(){
  int a = 0;
  f(&a + 1);
  f(0);
  f(&a);
}

Clang warns for the second call, but unfortunately not for the first one:

$ clang t.c
t.c:11:3: warning: null passed to a callee which requires a non-null argument
      [-Wnonnull]
  f(0);
  ^ ~
t.c:3:12: note: callee declares array parameter as static here
void f(int p[static 1])
           ^~~~~~~~~~~
1 warning generated.

The syntax may seem a little strange, but the C99 standardization committee obviously decided to reuse the pre-existing static keyword in a place that did not cause ambiguity so as to avoid the introduction of a new keyword (that could possibly break existing programs).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...