paddu123
paddu123

Reputation: 31

getting the variable values in #define definition

Here is what I am trying to do.

step1) I want to call a macro with a conditional statement(simple are compounded) like

for eg:

 MACRO1(a==1)
 MACRO1((i!=NULL) && (j>10))

step2) Here is how i am defining this macro

#define MACRO1(condition) \
        if(!(condition)) ??????????????????????????

Here in the definition of the macro, if the condition statement fails. I want to print the variable values so that I will be useful to know the exact reason. I used #condition in the definition, but it just printing the condition, instead of the values of the variables used in the condition. Please help.

Upvotes: 3

Views: 80

Answers (3)

There is no way that I know of to separate the variables from the condition. However, you can pass them in as extra parameters:

#define MACRO(condition, printsyntax, ...) \
    if(!(condition)) {\
        printf("condition %s not met! (" printsyntax ")\n", #condition, __VA_ARGS__); \
    };

You would use it as:

MACRO((i!=NULL) && (j>10), "i=%p, j=%d", i, j)

with an example result being:

condition (i!=NULL) && (j>10) not met! (i=(nil), j=11)

The compiler will splice together the constant strings into one string for the printf, the condition will automatically be printed and the rest of the arguments are your job to get right.

Edit

After Jens' remark about the else I modified the code a bit to not allow for such structures without using do{}while();.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78903

You shouldn't define macros that look like a function, but behave differently, in particular in your case may change control flow: an else that follows a macro that contains an if can apply to something different than the programmer (yourself after a week) thinks. Protect the if such that a dangling else will not apply to it

#define MACRO1(COND, ...)                                             \
  do {                                                                \
    if (!(COND)) printf(stderr, "condition " #COND ": " __VA_ARGS_);  \
 } while (0)

This macro should always be called with a format string as second argument and the names of the variables that you want to see

MACRO1((toto != 78.0), "toto=%9\n", toto);

this should print you something like

condition (toto != 78.0): toto=3.14

Upvotes: 2

jlahd
jlahd

Reputation: 6293

You could do something along these lines:

#define MACRO1(condition, msg) \
    if(!(condition)) { printf msg; }

and use it as follows:

MACRO1(a==1, ("a: %d\n", a))
MACRO1((i != NULL) && (j>10), ("i: %p, j: %d\n", i, j));

The C preprocessor is just a simple substitution engine, without the capability of analyzing the contents of expressions.

Upvotes: 3

Related Questions