0

I want to convert a string with / or . into an auto-generated variable name. So I need convert / or . into something acceptable by variable naming, such as __.

It's easy to do it with a function. But with macro, is it possible?

#define ROUTE(path, impl) \
char * k##path##_route = "{"#path":\""#impl"\"}"; // compilation failure for path like /usr/abc or ./abc

I can use impl to name the variable, but since multiple paths may map to the same impl, the compiler will complain about duplication for different paths with the same impl.

1 Answers1

0

But with macro, is it possible?

No. It is not possible to replace characters of an argument using the standard preprocessor.

acceptable by variable naming, such as __

__ is not an acceptable variable name because it is reserved to the implementation. As are all identifiers that contain consecutive underscores in C++.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Not contain, only start-with. `n__n` is a valid variable name for application use. – R.. GitHub STOP HELPING ICE Dec 18 '19 at 13:57
  • @R.. Yes contain. `n__n` is reserved. You may be confused with the rule that identifiers starting with underscore followed capital letter are also reserved. Also all identifiers starting with underscore followed by any character in global namespace. – eerorika Dec 18 '19 at 14:00
  • This question is tagged for 3 separate languages, so perhaps you have a different one in mind than I do (C). `n__n` is not reserved in C. – R.. GitHub STOP HELPING ICE Dec 18 '19 at 14:26
  • @R.. Oh, I didn't notice the language tags. My answer applies to C++. You may be correct regarding C. – eerorika Dec 18 '19 at 14:27
  • Since it's not the right way to solve my problem, I have changed my mind to solve it in another way: https://stackoverflow.com/questions/59394700/is-it-possible-to-use-line-in-the-auto-generated-variable-name-in-c. – Wayne Xiong Dec 20 '19 at 13:29