Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting, but the one comment I haven't seen yet on this thread is 'Why is this useful enough to be a compiler feature?'. I think this is especially relevant with a relatively slim language like C.

In the rare cases you need to do this sort of check why not just write a simple sizeof test?



The compiler doesn't pass any size information when you pass an array into a function. The function just gets a pointer. If you take the sizeof the array, you'll get the size of a pointer on your system:

[eric@rangely foo]$ cat foo.c

    #include <stdio.h>

    int test (int arr[10])
    {
        printf ("%lu\n", sizeof (arr));
        return 0;
    }

    int main (int argc, char *argv[])
    {
        int arr[5];
        test (arr);
        return 0;
    }
[eric@rangely foo]$ gcc foo.c -Wall -o foo && ./foo

8

(EDIT: fixed formatting)


As another poster said, the compiler can't know inside the function body the size of the array passed if you just use sizeof.

More to a style/safety point, if I ever see a function that expects an array and doesn't also take the size of that array as another parameter, that's a bug waiting to happen.

Especially in this case since this feature seems to only throw a warning on recent versions of clang, and more or less nothing else.


Wouldn't you need to put your sizeof test outside of every call to your function? Inside the function it would only know the declared parameter's type, so it would have no idea what sized array you actually passed.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: