Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you capitalize a pasted token in a macro?

Tags:

c

macros

In a C macro, is it possible to capitalize a pasted-in token? For example, I currently have the following macro:

#define TEST(name, keyword) \     test_##name:         TEST_##keyword##_KEYWORD 

I would invoke this as follows:

TEST(test1, TEST1) 

which would yield the following:

test_test1:     TEST_TEST1_KEYWORD 

Now, instead of having to type the same name twice (once with all lower case characters, and again with all upper case characters), is there any way that I could do either of the following, and either change the token into all uppercase letters or all lowercase letters?

TEST(test1) or TEST(TEST1) 

Thanks, Ryan

like image 230
DuneBug Avatar asked Aug 03 '10 20:08

DuneBug


People also ask

Should macro be capital letters?

It is not in uppercase, but it works. The use of uppercase for macros is a naming convention. The preprocessor can handle any case (upper, lower, mixed) in macro names.

What is token pasting?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.


2 Answers

As far as I'm aware, the only operations that can be done on tokens in the C preprocessor (at least ISO/ANSI standard) is to replace, 'stringify' or concatenate them. I'm also unaware of any GCC or MSVC extensions that will let you do what you want.

However, people have been coming up with clever (or oddball) ways to do magical (or horrible) things with macros, so I wouldn't be surprised if someone surprises me.

like image 137
Michael Burr Avatar answered Sep 20 '22 19:09

Michael Burr


You could do something like the following (untested, probably typos...)

#define NORMALIZE(TOK) NORMALIZE_ ## TOK 

and then for each of the writings that may occur do

#define NORMALIZE_test1 test1 #define NORMALIZE_TEST1 test1 

then use the NORMALIZE macro inside your real macro something like

#define TEST(name, keyword)                    \     test_ ## NORMALIZE(name):                  \         TEST_ ## NORMALIZE(keyword) ##_KEYWORD 

(but maybe you'd have to do some intermediate helper macros until you get all concatenations right)

like image 32
Jens Gustedt Avatar answered Sep 21 '22 19:09

Jens Gustedt