Question

Possible Duplicate:
How to single-quote an argument in a macro?

How can it do the following:

#define MACRO(X) ...
MACRO(a) // should give 'a'
Was it helpful?

Solution

I might be missing an easier way, but how about #define MACRO(X) ((#X)[0]). The # stringtizes X and then [0] selects the first character.

OTHER TIPS

Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:

There is no way to convert a macro argument into a character constant.

Like this:

#include <string>

std::string Macro(const std::string& s)
{
  std::string ret = "'";
  ret += s;
  ret += "'";
  return ret;
}

EDIT:

I posted this answer before it was revealed that this was needed for metaprogramming. I don not know of a way to accomplish this for metaprogramming, but metaprogramming is not my forte.

Also, as for why I am effectively saying "don't use the preprocessor" in the first place, read the comments below. But in short, I believe that almost everything that is commonly done using the preprocessor can and should be done using first-level constructs instead. Using the preprocessor skirts the C++ type system and reduces safety. Macros are difficult to debug, difficult to extend. Extensively using macros will result in code that isn't familiar to the programmers who didn't create the macro, resulting in a kind of "secret language" only 1 person knows, decreasing maintainability of not only the macros, but the functions where they are used.

OK, I guess that wasn't so short, but there it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top