My notes on variable arguments in C Macros

Like functions, we can also pass variable arguments to macros.

Similar to functions, we need to include ellipses (...) in macro definition.

__VA_ARGS__ is a varadic macro.

Declaration syntax is similar to varadic macro. A sequence of three full stops "..." is used to indicate that one or more arguments can be passed. During macro expansion each occurrence of __VA_ARGS__ in the macro replacement list is replaced by the passed arguments.

Example:

If we want to define our own printf() function, which also prints the file and line number.

// Our implemented function
void realdbgprintf (const char *SourceFilename,
                    int SourceLineno,
                    const char *CFormatString,
                    ...);
#define dbgprintf(...) realdbgprintf (__FILE__, __LINE__, __VA_ARGS__)

dbgprintf ("Hello, world"); expands to realdbgprintf (__FILE__, __LINE__, "Hello, world");

dbgprintf("%d + %d = %d", 2, 2, 5); expands to realdbgprintf(__FILE__, __LINE__, "%d + %d = %d", 2, 2, 5);




Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto