r/C_Programming • • 22d ago

Question What does the compiler do when we declare an array parameter's length as static?

I'm reading C Programming: A Modern Approach by K. N King

I'm on page 200 of that book, under the heading Using static in Array Parameter Declarations

The example given is: int sum_array(int a[static 3], int n)

And there is a short description:

Using static in this way has no effect on the behavior of the program. The presence of static is merely a “hint” that may allow a C compiler to generate faster instructions for accessing the array. (If the compiler knows that an array will always have a certain minimum length, it can arrange to “prefetch” these elements from memory when the function is called, before the elements are actually needed by statements within the function.)

So I was wondering, what exactly does a compiler do in this situation? Does it simply create a cache?

Also, what does it do line by line? How does the compiler the keyword static is in the context of a array parameter declaration?

If you were to write a compiler, and implement this feature, how would you do it (pseudocode)?

34 Upvotes

26 comments sorted by

23

u/tstanisl 22d ago

It has a few applications. For example it allows to express that arrays are non-empty.

bool foo(int arr[static 1]) {
    return arr;
}

bool bar(int arr[]) {
    return arr;
}

Compiling with -O3 produces:

"foo":
    mov     eax, 1
    ret
"bar":
    test    rdi, rdi
    setne   al
    ret

The compiler can assume that arr is never NULL in foo and optimize accordingly. See godbold.

Theoretically, it could help auto-vectorization or loop unrolling. But I haven't seen big impact of this feature yet.

2

u/SeriousPlankton2000 22d ago

I didn't code in C recently: Is "bool foo(int arr[1])" valid, too? (no "static") If yes, what's the difference?

8

u/aioeu 22d ago edited 22d ago

It's valid, but the 1 in that is effectively ignored.

That is long-standing behaviour, and it could not be changed... which is why this weird static thing was added instead.

(And don't try to find any relation between this use of static and the other ways static can be used in C. They're completely unrelated. By reusing the keyword static for different purposes the C committee avoided having to introduce a new keyword.)

0

u/[deleted] 20d ago

[deleted] — view deleted comment

2

u/aioeu 20d ago edited 20d ago

Any new keyword could have been used as an identifier in pre-existing code. That code would have been immediately broken by the change in the language.

It might have been possible to introduce a new keyword with the form reserved for the implementation (e.g. _Atleast), and possibly an associated header to define a regular all-lowercase macro (atleast) as well. But that's not what happened.

Another option would have been to introduce new syntax using punctuation. For instance, maybe:

int sum_array(int a[>= 3], int n) { ... }

could have been used. But again, that's not what happened.

Honestly, I really have no idea why static specifically was chosen — avoiding conflicts with existing identifiers is just my best guess. But if you have a look at the way the language syntax is specified in the C standard, it really does just allow static there as a keyword with its own distinct meaning, not static with its usual meaning as a storage class specifier.

It should be noted that C99 also started allowing type qualifiers to be used inside an array declarator for a function parameter. When the array type was adjusted to become a pointer type, these type qualifiers would be carried over. For instance, in:

void f(int a[restrict]) { ... }

this gets adjusted to:

void f(int * restrict a) { ... }

(Ditto for const and volatile, though they are arguably less useful.)

So maybe the C committee were thinking "well, static is sort of like that too", in the sense that storage class specifiers can be used in many of the places type qualifiers can be used.

2

u/flyingron 20d ago

Empty is fine in both cases (return 1 is correct). What it assumes in this case that nobody passes null into the function (but nothing prevents that no matter how you declare the array parameter).

11

u/aocregacc 22d ago

it can also help you catch bugs like the following:

int foo(int a[static 2]);

int bar() {
    int* a = malloc(sizeof *a);
    return foo(a);
}

Some compilers can see that the memory passed to foo here is smaller than the parameter indicates and warn you about it.

10

u/mjmvideos 22d ago

You could always write a little test program and have the compiler generate assembly code using different compiler options and see what it does.

6

u/Broad-Promise6954 22d ago

It's a special case added in the 1999 C standard. It promises that the pointer passed to a function points to the first of at least that many elements. Some of the committee members at the time were sure this was a great way to enable vectorization optimization in certain compilers.

4

u/rubidus-api 22d ago

I mostly use this for one thing: a pointer parameter that must not be NULL. As far as I know, [static 1] is the only way to say that in standard C (GCC and Clang also have __attribute__((nonnull)), but that's an extension). I picked it up from a YouTube video, and it's about the only place I use this syntax.

int get(int p[static 1]);

get(NULL);   /* GCC and Clang both warn: -Wnonnull */

It has limits, though. It only catches a NULL the compiler can see at compile time, such as a literal NULL. A pointer that might be NULL at run time passes without any warning, and no check is added at run time.

The promise also works against you. If a NULL does arrive at run time, that's undefined behavior, so the compiler may delete a NULL check inside the function.

    int use(int p[static 1])
    {
        if (!p)          /* removed at -O2 by GCC 14 and Clang 19 */
            return -1;
        return *p;
    }

GCC at least warns about this with -Wall (-Wnonnull-compare); Clang 19 removes it without a warning. So if the pointer comes from outside, check it before the call, not inside the function.

As for what the compiler does: it doesn't create a cache, and it generates no code for static itself. The parameter is still a plain pointer; the compiler just records a fact about it: "not NULL, and at least N elements can be read". You can see this in Clang's LLVM IR, where the parameter of int sum3(int a[static 3], int c) is marked dereferenceable(12) (three ints) and a plain int *a is not. So in a toy compiler, I'd store N on the parameter's type when parsing, and pass it on as that kind of attribute. The optimizer may then read the array earlier than the code says or drop NULL checks, and the warnings can catch calls with NULL or with an array that's too small.

The "prefetch" in the book is possible in principle, because the compiler knows those elements are safe to read. But in small tests with GCC 14 and Clang 19 at -O2, there were no prefetch instructions and no change in the loads; the only differences were the warnings and the removed NULL check. If you want to know for your own code, compare the assembly (-S, or Compiler Explorer) and benchmark it.

5

u/EpochVanquisher 22d ago

I believe it allows the compiler to reorder loads from a[3] more freely. This is usually not a big deal, and there are other ways to get the same effect.

1

u/Avikonette 22d ago

To wherewhat? x86_64 as Intel(R)?

1

u/mivanchev 22d ago

This is indispensable for catching bugs and the modern way of not ruining your relationship with the compiler and providing it hints. Use it as much as you can.

1

u/Linguistic-mystic 22d ago

The other answers don't mention an important other effect: it's a hint to the reader (maintainer) that communicates array size. This is indispensable and we should all use it whenever we know the size.

-3

u/flyingron 22d ago edited 22d ago

Welcome to the massive stupidity which is the C array type. Any time an array is mentioned in either a function parameter or a return type whether it was given a definite size or not, it is converted to a pointer to the type contained in the array. This was a short cut hack that was done in early C that they were never able to get away form (they did fix structs so they pass/return/assign properly).

By the way... have fun sometimes and print the sizeof a.

#include <stdio.h>

void foo(int pa[static 3] ) {
    printf("sizeof pa = %zu\n", sizeof pa);
}


int main() {

    int main_a[3];
    printf("sizeof main_a = %zu\n", sizeof main_a);
    foo(main_a);
}

sizeof main_a = 12
sizeof pa = 8 

The static thing is a red herring. It dates back to the days of very dumb compilers/optimizers. It's about as useful as declaring something register these days.

1

u/WittyStick 22d ago

It's about as useful as declaring something register these days.

register is actually more useful - iff you specify which register you want using extensions provided by GCC and Clang. Eg:

register int x __asm__("eax");

Will actually clobber eax for x.

But yeah, register without specifying which register is pointless.

1

u/SeriousPlankton2000 22d ago

You want to pass arrays by value?

3

u/flyingron 21d ago

If you ask it to do that, yes. The implicit conversion to pointer couild still be there when you wanted to do that.

The thing I never understood is why arrays don't assign. That's not a valid operation now, so adding it wouldn't "break" anything.

1

u/SeriousPlankton2000 21d ago

The biggest problem of C++ is that it's easy to accidentally ask it to copy a class / struct and thereby use the BFG9000 on your foot.

2

u/flyingron 21d ago

You can copy (and pass and return) structs in C just fine, too. That was fixed back around 1977. Nobody's shot their foot off yet.

1

u/SeriousPlankton2000 21d ago

Structs don't have a copy constructor that would be called twice per function call.

1

u/flyingron 20d ago

You're wrong about nine ways to Sunday.

First, while there are no copy constructors in C, they are copied. Yes, structs are copied when passed by value NOW. THIS IS WHAT PASSING BY VALUE means for every data type in the language, with the exception of the brain-damaged array construct.

In C++, there are VERY MUCH copy constructors for structs. If you don't declare one, one is implicitly defined for you. Structs are classes in C++. The only difference is that access is public by default.

1

u/SeriousPlankton2000 20d ago

My points are

  1. You usually want to avoid copying
  2. A defined copy constructor is a function call (vs. just copying)

2

u/flyingron 19d ago
  1. Is up to the programmer.
  2. You're still wrong.

1

u/SeriousPlankton2000 19d ago

OK, you are right and all the smart people (including my professor) are wrong.

→ More replies

-3

u/gnash117 22d ago

I agree with other commenters this will likely have zero effect with modern compilers.

The prefetch comment is about pulling memory from the hard drive (ssd) into ram and CPU cache. Time wise getting values from a SSD or even ram is quite an expensive operation. If your the compiler knows it needs that memory before it is used it can issue a prefetch instruction which basically tells the computer to start reading values before it is needed. Since the instruction is not involved with calculations, branching, or the final result most people never think about it but reducing SSD / ram / cache read time is one of the top ways to gain performance. High performance BLAS libraries often hand code the prefetch instructions. Compilers typically do better than humans since they have really complex code to insert the prefetch instructions at the most valuable instance in the code.