Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ macro '##' doesn't work after '->' operator

Tags:

I have a shared_ptr object x, which has get and set methods as follows:

x->a_value(); x->set_a_value(); x->b_value(); x->set_b_value(); 

When i try to define a macro:

#define MAC(type) \   x->set_##type##_value(val);  MAC(a) 

It works fine, but when I do:

#define MAC(type) \   x->##type##_value();  MAC(a) 

it gives the following compile error: pasting formed '->a', an invalid preprocessing token

like image 206
250 Avatar asked Apr 20 '18 08:04

250


People also ask

What is Argumented macro in C?

Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.


2 Answers

The preprocessor works on "tokens" - likes names and operators.

The ## operator creates a new token by pasting smaller parts together. In the first example set_##type##_value becomes set_a_value, which is a valid token.

In the second example ->##type##_value would become ->a_value, which is not a valid preprocessor token. It ought to be two tokens.

If you just make the line x->type##_value(); it should work. You get the separate tokens x, ->, a_value, (, ), and ;.

like image 71
Bo Persson Avatar answered Oct 12 '22 04:10

Bo Persson


What it says on the tin: ->a is not a single, valid preprocessor token: it's two tokens. You do not need to paste here.

#define MAC(type) \   x->type##_value(); 
like image 43
Quentin Avatar answered Oct 12 '22 02:10

Quentin