Skip to content

Instantly share code, notes, and snippets.

@larytet
Last active August 18, 2017 13:58
Show Gist options
  • Save larytet/8302251d513c088e4772b69fac414f27 to your computer and use it in GitHub Desktop.
Save larytet/8302251d513c088e4772b69fac414f27 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stddef.h>
// Based on https://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros
struct a
{
int a;
int b;
int c;
};
#define STRINGIZE(arg) STRINGIZE1(arg)
#define STRINGIZE1(arg) STRINGIZE2(arg)
#define STRINGIZE2(arg) #arg
#define CONCATENATE(arg1, arg2) CONCATENATE1(arg1, arg2)
#define CONCATENATE1(arg1, arg2) CONCATENATE2(arg1, arg2)
#define CONCATENATE2(arg1, arg2) arg1##arg2
#define FOR_EACH_1(what, x) \
what(x)
#define FOR_EACH_2(what, x, ...) \
what(x); \
FOR_EACH_1(what, __VA_ARGS__);
#define FOR_EACH_3(what, x, ...) \
what(x); \
FOR_EACH_2(what, __VA_ARGS__);
#define FOR_EACH_4(what, x, ...) \
what(x); \
FOR_EACH_3(what, __VA_ARGS__);
#define FOR_EACH_5(what, x, ...) \
what(x); \
FOR_EACH_4(what, __VA_ARGS__);
#define FOR_EACH_6(what, x, ...) \
what(x); \
FOR_EACH_5(what, __VA_ARGS__);
#define FOR_EACH_7(what, x, ...) \
what(x); \
FOR_EACH_6(what, __VA_ARGS__);
#define FOR_EACH_8(what, x, ...) \
what(x); \
FOR_EACH_7(what, __VA_ARGS__);
#define FOR_EACH_NARG(...) FOR_EACH_NARG_(__VA_ARGS__, FOR_EACH_RSEQ_N())
#define FOR_EACH_NARG_(...) FOR_EACH_ARG_N(__VA_ARGS__)
#define FOR_EACH_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N
#define FOR_EACH_RSEQ_N() 8, 7, 6, 5, 4, 3, 2, 1, 0
#define FOR_EACH_(N, what, ...) CONCATENATE(FOR_EACH_, N)(what, __VA_ARGS__)
#define FOR_EACH(what, ...) FOR_EACH_(FOR_EACH_NARG(__VA_ARGS__), what, __VA_ARGS__)
#define PRN_STRUCT_OFFSETS_(structure, field) printf(STRINGIZE(structure) ":" STRINGIZE(field)" - offset = %d\n", offsetof(structure, field));
#define PRN_STRUCT_OFFSETS(field) PRN_STRUCT_OFFSETS_(struct a, field)
int main(int argc, char *argv[])
{
FOR_EACH(PRN_STRUCT_OFFSETS, a);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment