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

Well, it could also solve the problem of sizeof(array) not working inside the function.

More specifically, at the moment, it evaluates to the size of the pointer itself, which is useless. On the other hand;

  static void
  foo(int a[..])
  {
    for (size_t i = 0; i < (sizeof a / sizeof int); i++)
    {
      // ...
    }
  }
... would be very useful, as it's the same syntax you can already use inside the function where the array is declared, which makes refactoring code into separate functions easier, as you don't have to replace instances of sizeof with your new size_t parameter name.

The only thing I'd like to see is compatibility with the static keyword; so that you can declare it as a sized-array but still indicate a compile-time minimum number of array elements. At the moment, in C99, this does not compile without serious diagnostics which would immediately highlight the problem:

  #include <stdio.h>

  static void
  foo(int a[static 4])
  {
    for (size_t i = 0; i < 4; i++)
      printf("%d\n", a[i]);
  }

  int
  main(void)
  {
    int a[] = { 1, 2, 3 };
    foo(a);     // Passing an array with 3 elements to a function that requires at least 4 elements
    foo(NULL);  // Passing no array to a function that requires an array with at least 4 elements
    return 0;
  }



  demo.c:14:3: warning: array argument is too small; contains 3 elements, callee requires at least 4 [-Warray-bounds]
  demo.c:15:3: warning: null passed to a callee that requires a non-null argument [-Wnonnull]


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

Search: