Advertisement
j3628800

C Macro Hackery

May 4th, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | Source Code | 0 0
  1. /**
  2.  * A nonexhaustive list of macro hackerys
  3.  */
  4.  
  5. /* -- default parameters from dev.to/rdentato (annotated) -- */
  6. /* vrg.h - reuseable for multiple programs */
  7. /* count how many args are passed to a variadic macro */
  8. #define vrg_cnt(vrg1, vrg2, vrg3, vrgN, ...) vrgN
  9. #define vrg_argn(...) vrg_cnt(__VA_ARGS__, 3, 2, 1, 0)
  10. /* concatenate name with number of args: "_MyFunc" + "1" -> "_MyFunc1" */
  11. #define vrg_cat0(x, y) x ## y
  12. #define vrg_cat(x, y) vrg_cat0(x, y)
  13. /* main macro used in definition */
  14. #define vrg(vrg_f, ...) vrg_cat(vrg_f, vrg_argn(__VA_ARGS__))(__VA_ARGS__)
  15.  
  16. /* example.c */
  17. #include "vrg.h"
  18. #include <stdio.h>
  19.  
  20. /* using the number of arguments to decide which function to call */
  21. #define MyFunc(...) vrg(_MyFunc, __VA_ARGS__)
  22. /* prepare a macro for every possible number of arguments */
  23. #define _MyFunc1(element) _MyFunc(element, -1, NULL)
  24. #define _MyFunc2(element, id) _MyFunc(element, id, NULL)
  25. #define _MyFunc3(element, id, pInput) _MyFunc(element, id, pInput)
  26. void *_MyFunc(void *element, int id, const void *pInput) {
  27.     printf("Calling MyFunc() with args %p, %d, %p\n", element, id, pInput);
  28. }
  29.  
Tags: macro hackery
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement