Skip to content

Instantly share code, notes, and snippets.

@irondoge
Created December 1, 2016 17:39
Show Gist options
  • Save irondoge/9488bba0e8b170afbee96fbea84a976a to your computer and use it in GitHub Desktop.
Save irondoge/9488bba0e8b170afbee96fbea84a976a to your computer and use it in GitHub Desktop.
Recursive variadic C/C++ macro. [compilation: gcc -std=c++11 macro.cpp]
#include <stdio.h>
#define PRINT(...) CAT(CT(__VA_ARGS__))(__VA_ARGS__)
#define CAT(N) DOG(N)
#define DOG(N) PRINT ## N
/* max supported args is 5 for now */
#define CT(...) VALS(__VA_ARGS__, 5, 4, 3, 2, 1)
#define VALS(N1, N2, N3, N4, N5, N, ...) N
#define PRINT1(A) printf("%d\n", A)
#define PRINT2(A, ...) printf("%d\n", A), PRINT1(__VA_ARGS__)
#define PRINT3(A, ...) printf("%d\n", A), PRINT2(__VA_ARGS__)
#define PRINT4(A, ...) printf("%d\n", A), PRINT3(__VA_ARGS__)
#define PRINT5(A, ...) printf("%d\n", A), PRINT4(__VA_ARGS__)
int main()
{
PRINT(42, 69, 360, 1337, 0);
return (0);
}
@cxw42
Copy link

cxw42 commented Aug 14, 2021

Thank you for this example, which works nicely (and has no warnings even with -Wall -Wpedantic :) ). What is the license? Much appreciated!

@irondoge
Copy link
Author

irondoge commented Oct 7, 2021

You're welcome ;)
Here is the license: http://www.wtfpl.net/
Enjoy!

@islee951031
Copy link

islee951031 commented Jan 18, 2024

Oh! It's really exact example which I have desired to find!!
Thank you!!!^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment