2

I was trying to define a general function to take input using _Generic in C, This is what I wrote

#include  <stdio.h>

#define readlong(x) scanf("%lld",&x);
#define read(x) scanf("%lld",&x);

#define scan(x) _Generic((x), \
long long: readlong, \
default: read \
)(x)

but when I compile it using gcc test.c -std=C11 on gcc 5.3.0, I get error:

error: 'readlong' undeclared (first use in this function)
Yogendra
  • 372
  • 3
  • 10

2 Answers2

1

You can define your helpers to be functions instead of macros. I modified scan so that it would pass the address to the matched function.

static inline int readlong (long long *x) { return scanf("%lld", x); }
static inline int readshort (short *x) { return scanf("%hd", x); }
static inline int unknown (void) { return 0; }

#define scan(x) _Generic((x), \
long long: readlong, \
short: readshort, \
default: unknown \
)(&x)
jxh
  • 69,070
  • 8
  • 110
  • 193
0
readlong

is not the variable that you have declared. In:

#define readlong(x) scanf("%11d",&x);

you added (x). This will not let you use readlong without them.

rgon91
  • 26
  • 1
  • I already tried changing `readlong` to `readlong(x)` but in that case I got error: `error: called object is not a function or function pointer #define scan(x) _Generic((x), \` – Yogendra Oct 17 '16 at 15:28