(C99) Expand a macro in another macro

I have a function in my program that takes 3 arguments. Several times in the code there is a macro defining 2 of these parameters.

So this is:

void func(int x, int y, int z){...}

It can be called as follows:

#define PAR 10,20
int z = 3;
func(PAR, z);

Now I need to change my code so that the function is called as a macro for another function.

#define func(X,Y,Z) func2(X,Y,Z,#Z)

This works fine if X and Y are really passed as variables. Is there a way to make it work with the PAR macro as well?

I am using GCC 4.6

+4
source share
2 answers

You can do this with an additional level of indirection, (ab) using variable macros:

#include <stdio.h>
#define PAR 2,3
#define F(...) G(__VA_ARGS__)
#define G(a,b,c) H(a,b,c)
void H(int a, int b, int c) {
  printf("%d %d %d\n", a , b, c);
}
int main() {
  F(PAR, 42);
  return 0;
}

Perhaps the best solution for the underlying problem.

+4
source

, .

#define func(X,Y,Z) func2(X,Y,Z,#Z)

. func (X, Y, Z) - . , func (PAR, Z).

- , , , (, func() - ), , func(). func2() , . , , , .

, , func (PAR, Z) , ,

13:12: error: macro "func" requires 3 arguments, but only 2 given

func (X, Y, Z) , X Y .

( , , " 3 14 3", ):

#include <stdio.h>
#include <stdlib.h>

#define PAR 10,20
#define MAR 3
#define WAR 14
#define func(X,Y,Z) print(X, Y, Z)

int Z = 3;

int main(void){

        func(MAR,WAR,Z);

        return 0;
}

void print(int x, int y, int c){

        printf("%d %d %d\n", x, y, c);

}

, ( , FYI).

+2

Source: https://habr.com/ru/post/1584999/


All Articles