3

Could I implement this in C?

#define X abc

then X_menu(); will be preprocessed as abc_menu();

In another build if I define X def then X_menu(); will be def_menu();

I'm sure there should be a method, but I could not figure out.

6
  • 1
    If users could do this then internal details of standard libraries would need to be named __l__i__k__e__t__h__i__s and also I would want to strangle people. Actually even that wouldn't work ... standard libraries would be impossible to implement safely. Commented Dec 15, 2014 at 20:29
  • The usual convention is not to play such tricks with the preprocessor. Even the (working) answer by Ryan Haining should not be used: The indirection adds a big speedbump for the reader, and the savings in typing is minimal. If you must some kind of automatic tool to shortcut your typing, use editior abbreviations. Learning to touch-type helps as well. Commented Dec 15, 2014 at 20:41
  • really don't understand this. Commented Dec 15, 2014 at 21:08
  • @user1932637 what I gave you works but is a bad idea to actually use Commented Dec 15, 2014 at 21:50
  • why do you think it's bad idea? Commented Dec 15, 2014 at 23:01

1 Answer 1

4

No, you wouldn't want this behavior as it would be very unsafe and difficult to deal with replacing every X in every name. However, you could use a macro function to do something similar

#define X(F) abc##F
X(_menu();)

## is macro concatenation, so X(_menu();) will expand to abc_menu();

As Roger points out, the macro will also work with the syntax

X(_menu)();

which you may find easier to read

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

3 Comments

X(_menu)(); is easier on the eye, imo.
Ha, it's tricky. cool! the only thing I don't like is you have to define X(F) rather than X. is there another to solve it?
@user1932637 afaict, nothing nicer than this while still only using the preprocessor, if you start doing your own code generation then the possibilities are endless

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.