Skip to content

Instantly share code, notes, and snippets.

@garettbass
Last active May 30, 2019 23:27
Show Gist options
  • Save garettbass/aaf91455330f7f73a82d7b2ed2cab605 to your computer and use it in GitHub Desktop.
Save garettbass/aaf91455330f7f73a82d7b2ed2cab605 to your computer and use it in GitHub Desktop.
Some utilities for C arrays
#pragma once
#include <assert.h>
#define must_be_array(a)\
_Pragma("GCC diagnostic push")\
_Pragma("GCC diagnostic error \"-Wincompatible-pointer-types\"")\
((void)sizeof(((char(*)(typeof(a[0])(*)[sizeof(a)/sizeof(a[0])]))0)(&a)))\
_Pragma("GCC diagnostic pop")\
// returns the length of the provided array
#define lengthof(a) (must_be_array(a),(sizeof(a)/sizeof(a[0])))
// returns a pointer after the last element of the array
#define endof(a) (must_be_array(a),(&a)[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment