Home > front end >  Is it possible to truncate C preprocessor identifiers?
Is it possible to truncate C preprocessor identifiers?

Time:07-30

In C, with #define, we can use the token pasting operator ## to concatenate an identifier with some other text.

Is it possible to do the reverse as seen in the example below?

#define millimeter
//truncate to milli
//convert to millisecond

I am specifically trying to use this for function name generation, so a call to a non-existent function millimeter() can generate code containing millisecond.

The previous paragraph is an example of how I would use this. I have included it for context, but I am not sure if that is possible even if the identifier can be truncated. If you can link related questions for this part, that would be helpful.

CodePudding user response:

Terrible code adapted from this answer: https://stackoverflow.com/a/37355243/1046249

TRUNCATE(x) will do the reverse of paste by truncating a predefined set of tokens. Then CAT(x,y) pastes y onto the end of x so CAT(TRUNCATE(millimeter),second)() becomes millisecond().

I have no idea why you would ever want to do this.

#define TRUNCATE_millimeter  milli
#define TRUNCATE_milligram   milli

#define TRUNCATE(s) TRUNCATE_ ## s

#define _CAT(x,y) x ## y
#define CAT(x,y) _CAT(x,y)

int millisecond() {
    return 0;
}

int main()
{
    CAT(TRUNCATE(millimeter), second)();
    CAT(TRUNCATE(milligram), second)();

    return 0;
}

CodePudding user response:

The units of input to the C preprocessor are (preprocessing) tokens such as identifiers, operators, and string literals. Tokens are atomic as far as the preprocessor is concerned -- it has no mechanism for dividing them into pieces or for operating in any other way on partial tokens.

Under some circumstances, you can use macro substitution to emulate truncation of a pre-selected (by you) set of specific tokens that have the form of identifiers or keywords, but this is not generalizable.

I am specifically trying to use this for function name generation

Where this sort of thing is done, it is generally done by pasting tokens together, not truncating them.

  • Related