0

I have the following method for various test cases:

test_case(mystruct->myvar1, "myvar1", ...);
test_case(mystruct->myvar2, "myvar2", ...);
test_case(mystruct->myvar3, "myvar3", ...);

Is there a way i can avoid having to type myvar1 twice, once as the variable and once as a string. ?

2 Answers 2

2

Sure there is.

The question is is that a good idea?

#define MY_TEST(object, value, ...)     do { test_case(object->value, #value , __VARARGS__); } while(false)

Code:

MY_TEST(mystruct, myvar1, ...);
MY_TEST(mystruct, myvar2, ...);
MY_TEST(mystruct, myvar3, ...);

Excplanation:

In the macro:

#define MY_TEST(object, value, ...)

The words: object and value become parameters to the macro. And are replaced identically in the expression on the right. If a parameter is prefixed with # then it is stringified by adding double quotes around it.

 object->value, #value    =>  object->value, "value"

Macros can also have a variable argument list represented by the ... which is replaced by using __VARARGS__ on the destination side. There is one limitation with using varargs in that it must match at least one parameter (i.e it can not match zero parameters (they may have fixed that but not sure)).

The reason to add the do { ... } while(false) is me being pedantic when using macros to make sure that the expression is treated like a statement. The compiler will optimize this away so there is no extra code and the statement is executed exactly once. I find it good practice to be overly careful and pedantic when using macros as there is little protection from the pre-processor (and the language has tried to evolve away from using macros in the first place).

Sign up to request clarification or add additional context in comments.

1 Comment

An excellent and correct answer, but just to reiterate: Is this a good idea? You only have to write the code once, but you (and potentially others) have to read it several times. I can tell, to a reasonable extent, what test_case(mystruct->myvar1, "myvar1", ...) using simple C++ rules, but I have no idea what MY_TEST(mystruct, myvar1, ...) does without going and looking up the macro definition.
0

You can use stringify:

#define F(a) a, #a
F(x) // x, "x"

3 Comments

yes, but i a getting mystruct->myvar1 instead of just myvar1 then i have to do string processing
You can add whatever you want in the macro, including mystruct->a, #a.
i dont understand can you show an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.