Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Created March 7, 2025 10:22
Show Gist options
  • Save crosstyan/518d7dcc29d23a1abb73cd6fd6a8c1c4 to your computer and use it in GitHub Desktop.
Save crosstyan/518d7dcc29d23a1abb73cd6fd6a8c1c4 to your computer and use it in GitHub Desktop.
#ifndef _Static_assert
/* https://en.cppreference.com/w/c/language/_Static_assert
* https://en.cppreference.com/w/c/keyword/static_assert
* check if C23 or C++
*/
#if defined(__cplusplus) || \
(defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L)
#define _Static_assert static_assert
#else
#include <assert.h>
#endif /* defined(__cplusplus) || defined(__STDC_VERSION__) */
#endif /* _Static_assert */
#ifdef __CHECKER__
#define __BUILD_BUG_ON_ZERO_MSG(e, msg) (0)
#else /* __CHECKER__ */
#define __BUILD_BUG_ON_ZERO_MSG(e, msg) \
((int)sizeof(struct { _Static_assert(!(e), msg); }))
#endif /* __CHECKER__ */
#ifndef __same_type
/* Are two types/vars the same type (ignoring qualifiers)? */
#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
#endif
#ifndef __must_be_array
/* &a[0] degrades to a pointer: a different type from an array */
#define __must_be_array(a) \
__BUILD_BUG_ON_ZERO_MSG(__same_type((a), &(a)[0]), "must be array")
#endif
#ifndef ARRAY_SIZE
/**
* ARRAY_SIZE - get the number of elements in array @arr
* @arr: array to be sized
*/
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) + __must_be_array(arr)
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment