1

Normally you would write a scanf function call like below:

scanf("%d %d %d", &num1, &num2, &num3);

I would like to have a macro function that goes something like this:

#define REP_FORMAT(X) "%d " * X

// Usage:
scanf(REP_FORMAT(3), &num1, &num2, &num3);

Is this possible?

yoduh
  • 7,074
  • 2
  • 11
  • 21
Zombie Chibi XD
  • 370
  • 3
  • 17
  • 4
    Honestly this is why `for` loops exist. Just `scanf()` N times. – tadman Nov 03 '22 at 03:55
  • 2
    Tip: Instead of a sequence of variables, use an *array* of the same type. – tadman Nov 03 '22 at 04:03
  • Related: [How can I fix `scanf` to take data into an array](https://stackoverflow.com/a/72178652/60281) (And, seriously, *do* read that answer, it's full of good advice.) – DevSolar Nov 03 '22 at 04:23

1 Answers1

1

This type of bounded repetition is not possible using the C-standard preprocessor alone for an arbitrary number of repetitions.

However for a given maximum number of repetitions you can get something that probably meets your needs with code like:

#define REP_FORMAT_0 ""
#define REP_FORMAT_1 "%d"
#define REP_FORMAT_2 "%d " REP_FORMAT_1
#define REP_FORMAT_3 "%d " REP_FORMAT_2
#define REP_FORMAT_4 "%d " REP_FORMAT_3
#define REP_FORMAT_5 "%d " REP_FORMAT_4
#define REP_FORMAT_6 "%d " REP_FORMAT_5
#define REP_FORMAT_7 "%d " REP_FORMAT_6
#define REP_FORMAT_8 "%d " REP_FORMAT_7
#define REP_FORMAT(x) REP_FORMAT_##x

This code assumes your argument to REP_FORMAT is a literal non-negative integer less than 9 (as shown in the question), and not an expression or variable.

Dan Bonachea
  • 2,408
  • 5
  • 16
  • 31
  • Identifiers starting with `_` and an upper case letter are reserved. We can't use them. https://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html – KamilCuk Nov 05 '22 at 07:29
  • @kamicuk you are technically correct, although this almost never causes a problem in practice. Nevertheless I've edited the answer to address your concern. – Dan Bonachea Nov 05 '22 at 20:18