Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to single-quote an argument in a macro?

I would like to create a C pre-processor macro that will single-quote the argument. Just like the common used #X.

I want Q(A) to be expanded to 'A'.

I am using gcc on Linux.

Does any one have an idea?

I know # double-quotes. I am looking for a similar mechanism for single-quoting.

like image 309
eyalm Avatar asked Jan 15 '10 15:01

eyalm


People also ask

How do you write a macro argument?

To create a macro with arguments, put them in parentheses separated by commas after the macro name, e.g. then BadSquare(3+4) would give 3+4*3+4, which evaluates to 19, which is probably not what we intended.

What is a macro argument?

Macro Arguments (DEFINE-! ENDDEFINE command) The macro definition can include macro arguments, which can be assigned specific values in the macro call. There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.

Can you use single quotes in C++?

In C and C++ the single quote is used to identify the single character, and double quotes are used for string literals. A string literal “x” is a string, it is containing character 'x' and a null terminator '\0'. So “x” is two-character array in this case.

Can a macro argument be converted to constant?

There is no way to convert a macro argument into a character constant. If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros. s is stringified when it is used in str, so it is not macro-expanded first.


1 Answers

The best you can do is

#define Q(x) ((#x)[0])

or

#define SINGLEQUOTED_A 'A'
#define SINGLEQUOTED_B 'B'
...
#define SINGLEQUOTED_z 'z'

#define Q(x) SINGLEQUOTED_##x

This only works for a-z, A-Z, 0-9 and _ (and $ for some compilers).

like image 158
kennytm Avatar answered Jan 01 '23 08:01

kennytm