Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is [static 1] not used everywhere in C?

I saw a Video about modern C programming, and one topic was that when you use [static 1] with a parameter, it indicates to the reader and the compiler that a pointer should never be NULL.

You would use it like this:

void foo(int my_ptr[static 1]) {
    // my_ptr should never be NULL
}

instead of:

void foo(int* my_ptr) {
    // my_ptr can be NULL
}

If you enable -Wnonnull, it even throws a warning when you pass NULL to the first option. My question is, why is this not common practice and used everywhere?

I don't think this can or should replace NULL checks, but it certainly would be useful, nevertheless, IMO.

I also heard that compilers might remove NULL checks if they see that the pointer should never be NULL because of the [static 1], which would be bad, but I don't know if this is true.

like image 259
Finn Avatar asked Oct 15 '25 15:10

Finn


1 Answers

  • Although this was introduced as early as C99, as mentioned in an answer here What does the static keyword do in C?, compilers had very poor support for this until just a few years back, around the time when that post was written (around gcc 11/clang 13).

  • Compilers are only able to do this check caller-side for compile-time constants. It has no effect on run-time assigned pointers, making the feature less useful and misleading even, if the programmer thinks they are now safe from null pointers.

  • Good program design is to do checks against null pointers at the point where something risk becoming a null pointer. And not in some unrelated function later on. For example, the check should be done after calling some function that might return a null pointer.

    Adding a null pointer check inside some unrelated function on the other hand, introduces a branch which is useless overhead in case the caller is not passing trash parameters to the function. Which can turn out very expensive if the function is called repeatedly from a loop etc.

So it really boils down to: that parameter shouldn't be null anyway. Or otherwise there's a caller-side bug. However, [static 1] might serve as self-documenting code, telling the caller "I'm not doing any null pointer checks here so you better not pass me garbage parameters". That's generally the spirit of C - to leave error handling to the caller.

like image 87
Lundin Avatar answered Oct 17 '25 05:10

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!