Skip to content

Instantly share code, notes, and snippets.

@chuntaro
Created March 7, 2023 10:40
Show Gist options
  • Select an option

  • Save chuntaro/408817a336606fecff9a930081e27f7f to your computer and use it in GitHub Desktop.

Select an option

Save chuntaro/408817a336606fecff9a930081e27f7f to your computer and use it in GitHub Desktop.
C 言語で型安全・個数安全なオプショナル引数を実現する
#include <stdio.h>
//----------------------------------------------------------------
#define INDEX_RSEQ() 4, 3, 2, 1, 0
#define VA_ARGS_SIZE_IMPL(ARG1, ARG2, ARG3, ARG4, N, ...) N
#define VA_ARGS_SIZE_AUX(...) VA_ARGS_SIZE_IMPL(__VA_ARGS__)
#define VA_ARGS_SIZE(...) VA_ARGS_SIZE_AUX(__VA_ARGS__, INDEX_RSEQ())
#define CONCATENATE_AUX(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_AUX(x, y)
//----------------------------------------------------------------
//----------------------------------------------------------------
// int add(int a, int b = 0, int c = 0);
#define add(...) CONCATENATE(add, VA_ARGS_SIZE(__VA_ARGS__))(__VA_ARGS__)
int add3(int a, int b, int c)
{
return a + b + c;
}
int add2(int a, int b)
{
return add3(a, b, 0);
}
int add1(int a)
{
return add2(a, 0);
}
//----------------------------------------------------------------
int main(void)
{
printf("add(1) => %d\n", add(1)); // => add(1) => 1
printf("add(1, 2) => %d\n", add(1, 2)); // => add(1, 2) => 3
printf("add(1, 2, 3) => %d\n", add(1, 2, 3)); // => add(1, 2, 3) => 6
// ↓add4 が無いというリンクエラー
// printf("add(1, 2, 3, 4) => %d\n", add(1, 2, 3, 4));
return 0;
}
// 参考
// https://in-neuro.hatenablog.com/entry/2020/10/21/155651
// https://stackoverflow.com/questions/9179940/does-c-support-optional-null-parameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment