array_length.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* The array_length and array_end macros.
  2. Copyright (C) 2017-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #ifndef _ARRAY_LENGTH_H
  16. #define _ARRAY_LENGTH_H
  17. /* array_length (VAR) is the number of elements in the array VAR. VAR
  18. must evaluate to an array, not a pointer. */
  19. #define array_length(var) \
  20. (sizeof (var) / sizeof ((var)[0]) \
  21. + 0 * sizeof (struct { \
  22. _Static_assert (!__builtin_types_compatible_p \
  23. (__typeof (var), __typeof (&(var)[0])), \
  24. "argument must be an array"); \
  25. }))
  26. /* array_end (VAR) is a pointer one past the end of the array VAR.
  27. VAR must evaluate to an array, not a pointer. */
  28. #define array_end(var) (&(var)[array_length (var)])
  29. /* array_foreach (PTR, ARRAY) iterates over all the elements in an
  30. array, assigning the locally defined pointer variable PTR to each
  31. element in turn.
  32. array_foreach_const (PTR, ARRAY) does the same, but *PTR is declared
  33. const even if the array is not. */
  34. #define array_foreach(ptr, array) \
  35. for (__typeof ((array)[0]) *ptr = (array) ; \
  36. ptr < array_end (array) ; ptr++)
  37. #define array_foreach_const(ptr, array) \
  38. for (const __typeof ((array)[0]) *ptr = (array) ; \
  39. ptr < array_end (array) ; ptr++)
  40. #endif /* _ARRAY_LENGTH_H */