Mark Summerfield
2024-08-05 08:26:04 UTC
Given
```
// vaargs.h
#pragma once
#define NARGS(...) NARGS_(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define NARGS_(_5, _4, _3, _2, _1, N, ...) N
#define CONC(A, B) CONC_(A, B)
#define CONC_(A, B) A##B
// va_test.h
#include "vaargs.h"
#define va_test(...) CONC(va_test, NARGS(__VA_ARGS__))(__VA_ARGS__)
int va_test0();
int va_test1(int);
int va_test2(int, int);
// va_test.c
#include "va_test.h"
int va_test0() { return va_test2(3, 11); }
int va_test1(int a) { return va_test2(3, a); }
int va_test2(int a, int b) { return a + b; }
// va_tests.c
#include "va_test.h"
#include <stdbool.h>
#include <stdio.h>
int main() {
int i = va_test();
if (i != 14) {
fprintf(stderr, "FAIL: va_test() expecte 14 go %d\n", i);
}
i = va_test(5);
if (i != 8) {
fprintf(stderr, "FAIL: va_test() expecte 8 go %d\n", i);
}
i = va_test(2, 9);
if (i != 11) {
fprintf(stderr, "FAIL: va_test() expecte 11 go %d\n", i);
}
}
```
This does *not* work for the `va_test()` call. But if I supply 1 or 2 args
it works great.
The rational is that I'd like to create a function `new_thing()` which
takes an optional size, e.g.,
```
thing new_thing0() { return new_thing1(10); }
// above uses default size of 10
thing new_thing1(int size) { ... }
```
```
// vaargs.h
#pragma once
#define NARGS(...) NARGS_(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define NARGS_(_5, _4, _3, _2, _1, N, ...) N
#define CONC(A, B) CONC_(A, B)
#define CONC_(A, B) A##B
// va_test.h
#include "vaargs.h"
#define va_test(...) CONC(va_test, NARGS(__VA_ARGS__))(__VA_ARGS__)
int va_test0();
int va_test1(int);
int va_test2(int, int);
// va_test.c
#include "va_test.h"
int va_test0() { return va_test2(3, 11); }
int va_test1(int a) { return va_test2(3, a); }
int va_test2(int a, int b) { return a + b; }
// va_tests.c
#include "va_test.h"
#include <stdbool.h>
#include <stdio.h>
int main() {
int i = va_test();
if (i != 14) {
fprintf(stderr, "FAIL: va_test() expecte 14 go %d\n", i);
}
i = va_test(5);
if (i != 8) {
fprintf(stderr, "FAIL: va_test() expecte 8 go %d\n", i);
}
i = va_test(2, 9);
if (i != 11) {
fprintf(stderr, "FAIL: va_test() expecte 11 go %d\n", i);
}
}
```
This does *not* work for the `va_test()` call. But if I supply 1 or 2 args
it works great.
The rational is that I'd like to create a function `new_thing()` which
takes an optional size, e.g.,
```
thing new_thing0() { return new_thing1(10); }
// above uses default size of 10
thing new_thing1(int size) { ... }
```