Home > Software design >  C pre-processor define directive with multiple replacements
C pre-processor define directive with multiple replacements

Time:01-21

/*
 * Recommended alloc parameters for "small" contexts that are never expected
 * to contain much data (for example, a context to contain a query plan).
 */

    #define ALLOCSET_SMALL_MINSIZE   0
    #define ALLOCSET_SMALL_INITSIZE  (1 * 1024)
    #define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)
    #define ALLOCSET_SMALL_SIZES \
        ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE

I don't understand last marco, I use

printf("%d", ALLOCSET_SMALL_SIZES);

then warning:

warning: too many arguments for format [-Wformat-extra-args]

and also return 0.

similar post I found: #define directive with multiple replacements?


Update: Jumped around source code, got it.
function like

foo(size_t,size_t,size_t)

can just use

foo(ALLOCSET_DEFAULT_SIZES)

CodePudding user response:

Given the following snippet:

#define ALLOCSET_SMALL_SIZES \
        ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE

The macro ALLOCSET_SMALL_SIZES gets replaced with:

ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE

which gets replaced with:

0,
(1 * 1024),
(8 * 1024)

which are separate arguments. Then in the call to printf ():

printf("%d", ALLOCSET_SMALL_SIZES);

ALLOCSET_SMALL_SIZES gets replaced with 0, (1 * 1024), (8 * 1024)

Or,

printf ("%d", 0, (1 * 1024), (8 * 1024));

Hence the warning.


Fix:

Replace it with:

printf ("%d %d %d", 0, (1 * 1024), (8 * 1024));

See: Why use Macros in C? and What are C macros useful for?

  •  Tags:  
  • c
  • Related