Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a variadic macro that uses the names of the arguments passed

I want to write a variadic macro that somehow knows the names of the arguments passed. For example:

The code:

int x = 2;
float f = 4.6;
char c = 'A';
char* str = "Bla bla";
PRINT("%d  %f %c  %s", x, f, c, str);     // calling the macro

shall produce the output

x=2 f=4.6 c=A str=Bla bla.

Hope someone knows the answer to that.

like image 278
user3115040 Avatar asked Feb 14 '23 05:02

user3115040


1 Answers

Close but not exactly (only works for single expression) what the asker required:

#define PRINT(fmt, var) printf(#var " = " fmt, (var))

Here is an example:

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

#define PRINT(fmt, var) printf(#var " = " fmt, (var))

int
main(int argc, char *argv[])
{
    int x = 2, y = 3;
    float f = 4.6;
    char c = 'A';
    char *str = "Bla bla";
    PRINT("%d\n", x);
    PRINT("%f\n", f);
    PRINT("%c\n", c);
    PRINT("%s\n", str);
    PRINT("%d\n", x+y);
    exit(EXIT_SUCCESS);
}
like image 177
Lee Duhem Avatar answered Apr 27 '23 10:04

Lee Duhem