Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand macro inside string literal

What I'm trying to do is to #define a macro:

#define a(2) 

and later use it inside a string literal: string = "a";.

I want that string to be interpreted not as string but to get the value of a, i.e. 2. I didn't succeed, can anybody help?

like image 583
Amine Avatar asked Dec 17 '13 10:12

Amine


People also ask

What does the '#' symbol do in macro expansion?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

How do you define a string macro?

We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2.

What is literal in string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

What is Stringify in C++?

“Stringification” means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in “foo (z)” . In the C & C++ preprocessor, stringification is an option available when macro arguments are substituted into the macro definition.


2 Answers

#define STRINGIFY2(X) #X #define STRINGIFY(X) STRINGIFY2(X) #define A 2 

Then STRINGIFY(A) will give you "2". You can concatenate it with other string literals by putting them side by side.

"I have the number " STRINGIFY(A) "." gives you "I have the number 2.".

like image 162
Simple Avatar answered Oct 02 '22 10:10

Simple


No, you cannot do macro expansion INSIDE string literals (i.e. having the preprocessor to look inside literals for macros to expand).

You can have a macro expansion to produce a string literal using the stringify operator (#). But that's a different thing.

like image 25
6502 Avatar answered Oct 02 '22 11:10

6502