What does "#define STR(a) #a" do? - c++

I'm reading the phoneME's source code. It's a FOSS JavaME implementation. It's written in C++, and I stumbled upon this:
// Makes a string of the argument (which is not macro-expanded)
#define STR(a) #a
I know C and C++, but I never read something like this. What does the # in #a do?
Also, in the same file, there's:
// Makes a string of the macro expansion of a
#define XSTR(a) STR(a)
I mean, what's the use of defining a new macro, if all it does is calling an existing macro?
The source code is in https://phoneme.dev.java.net/source/browse/phoneme/releases/phoneme_feature-mr2-rel-b23/cldc/src/vm/share/utilities/GlobalDefinitions.hpp?rev=5525&view=markup. You can find it with a CTRL+F.

In the first definition, #a means to print the macro argument as a string. This will turn, e.g. STR(foo) into "foo", but it won't do macro-expansion on its arguments.
The second definition doesn't add anything to the first, but by passing its argument to another macro, it forces full macro expansion of its argument. So XSTR(expr) creates a string of expr with all macros fully expanded.

# is the stringizing operator. The preprocessor makes a string out of the parameter.
Say you have:
STR(MyClass);
It would be preprocessed as:
"MyClass";
The level of indirection (using XSTR()) has to do with macro expansion rules.

First, you should know that this pair of macros is actually fairly common. The first does exactly what the comment says -- it turns an argument into a string by enclosing it in double quotes.
The second is used to cause macro expansion of the argument. You typically use them together something like this:
#define a value_a
printf("%s", XSTR(a));
The macro expansion will expand a out to string_a, and the stringify will turn that into a string, so the output will be value_a.

The #a is referred to as the stringizer operator. It takes the formal parameter, in this case a, and turns it in to a string by enclosing it in double quotes.
So if you have:
string s = STR("my quoted string");
cout << s;
The output would be:
"my quoted string"

Related

Getting a string of class variable via macro?

I have the following method for various test cases:
test_case(mystruct->myvar1, "myvar1", ...);
test_case(mystruct->myvar2, "myvar2", ...);
test_case(mystruct->myvar3, "myvar3", ...);
Is there a way i can avoid having to type myvar1 twice, once as the variable and once as a string. ?
Sure there is.
The question is is that a good idea?
#define MY_TEST(object, value, ...) do { test_case(object->value, #value , __VARARGS__); } while(false)
Code:
MY_TEST(mystruct, myvar1, ...);
MY_TEST(mystruct, myvar2, ...);
MY_TEST(mystruct, myvar3, ...);
Excplanation:
In the macro:
#define MY_TEST(object, value, ...)
The words: object and value become parameters to the macro. And are replaced identically in the expression on the right. If a parameter is prefixed with # then it is stringified by adding double quotes around it.
object->value, #value => object->value, "value"
Macros can also have a variable argument list represented by the ... which is replaced by using __VARARGS__ on the destination side. There is one limitation with using varargs in that it must match at least one parameter (i.e it can not match zero parameters (they may have fixed that but not sure)).
The reason to add the do { ... } while(false) is me being pedantic when using macros to make sure that the expression is treated like a statement. The compiler will optimize this away so there is no extra code and the statement is executed exactly once. I find it good practice to be overly careful and pedantic when using macros as there is little protection from the pre-processor (and the language has tried to evolve away from using macros in the first place).
You can use stringify:
#define F(a) a, #a
F(x) // x, "x"

A previously defined constant, given as macro argument, is considered as string literal

Let's say I have defined a macro which does this
#define MY_MACRO(NAME) \
std::string get##NAME() const \
{ \
return doSomething(#NAME); \
}
Where doSomething method signature will be something like this
std::string doSomething(const std::string& parameter);
This works pretty well when the NAME macro parameter has no dashes in it.
For example :
#define MY_MACRO(thisIsA_test) // Works
But, when I have a dash in my string (this can happen) it won't work because dashes are not allowed in method names
#define MY_MACRO(thisIsA-test) // does NOT WORK
I have tried to work it around this way
#define thisIsAtest "thisIsA-test"
#define MY_MACRO(thisIsAtest)
Everything compiles just fine and I have the getthisIsAtest method generated but unfortunately the macro is not resolved and "thisIsAtest" is kept as string literal.
In other words the doSomething parameter string value will be "thisIsAtest" whereas I was expecting "thisIsA-test".
To expand the macro argument, just use an indirection macro.
#define stringize_literal( x ) # x
#define stringize_expanded( x ) stringize_literal( x )
Your use-case:
return doSomething( stringize_expanded( NAME ) );
Now the method will be named with name of the macro, and the function will be called with the contents of the macro. Somewhat questionable in terms of organization, but there you have it.
Why it works:
By default, macro arguments are expanded before being substituted. So if you pass thisIsAtest to parameter NAME, the macro expansion will replace NAME with "thisIsA-test". The pre-expansion step does not apply when you use a preprocessor operator # or ## though.
In your original code, one use of NAME is subject to ## and the other is subject to # so the macro definition of thisIsAtest never gets used. I just introduced a macro stringize_expanded which introduces an artificial use of NAME (via x) which is not subject to an operator.
This is the idiomatic way to use # and ##, since the expansion is desired more often than the literal macro name. You do happen to want the default behavior for ## in this case, but it could be considered a case of poor encapsulation (as the name of an interface is used to produce output), if you wanted to apply real programming principles to the problem.
There's nothing to work around.
As you have said yourself, dashes are not valid in function names.
So, do not use them.

How to define a pattern in macro in C++?

I have a file having too many section like
[Section]
[Section.Ia32]
[Section.x64].... so more
so, I need to define single macro to when parsing the file we can get the section using one macro. currently I am trying like,
#define APattern = "(^(\\s)*\\[Section(\\.\\w+)*\\])";
it's compile succesfully... but it is not working.
For e.g
CString a = Section;
a.compareNoCase(APattern);
it is not working..
thanks
I think the syntax in your define is incorrect. In c++ a
define
is without
"=",
rather like
#define SQR(a) (a * a).
So in your define an argument is missing as well. Do not use the
";"
at the end of the line.
And for second, you are passing the result as an argument to the function
a.compareNoCase(),
which might be incorrect in meaning of which type is returned by your define.
With #define everything you have after the name is just pasted. So for yuor example the result will be:
CString a = Section;
a.compareNoCase( = "(^(\\s)*\\[Section(\\.\\w+)*\\])"; );
You can see for yourself it is invalid syntax. For correct definition you an go backwards:
a.compareNoCase( "(^(\\s)*\\[Section(\\.\\w+)*\\])" );
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-->
#define APattern "(^(\\s)*\\[Section(\\.\\w+)*\\])"
I think you have 2 problems, the first one, regarding C macro syntax, rightly addressed by fiscblog answer (+1), the other is that seems you are actually expecting a regular expression match, that is over CString capabilities. See for instance this answer to get regular expressions matching working in Visual C++
To be true, I would address the problem using sscanf, more or less like
#define ASection(In, Section) (sscanf(In, " [Section(%^[)])", Section) == 1)

C++ macro - pass as "parameter" next word instead of in ()

This code:
#define DEREF(ptr) (*ptr)
MyClass *pClass = new MyClass;
DEREF(pClass).foo(); // equivalent of (*pClass).foo() or simply pClass->foo()
Can I configure the #define macro to accept the ptr parameter as the word that follows the macro instead of bracketed statement, so that I can do the following?:
DEREF pClass.foo();
No, C macros can only receive parameters inside brackets '()'
Can I configure the #define macro to accept the ptr parameter as the word that follows the macro
No. You can, however, write custom code preprocessor that will transform your code before passing it to C++ compiler. This is not really simple or practical but can be done. moc in qt 4 operates this way - scans for custom keywords and replaces them with C++ statements compiler can accept. This allows Qt 4 to implement its "signal/slot" mechanism.

Macro expansion in C++

How can I define a macro (or a workaround for this) where the parameter is at the beginning of the line?
#define SINGLETON_IMPLEMENTATION(className) \
##className* ##className::instance_ = NULL;
This give a compiler warning (GCC 3.2.3): " '##' cannot appear at either end of a macro expansion"
You only need ## to append a parameter to another string. Your macro can be recast as
#define SINGLETON_IMPLEMENTATION(className) \
className* className::instance_ = NULL;
## is the concatenation operator; the compiler is just complaining about that.
You cannot concatenate a token without something before it, i.e. at the beginning of the macro expansion; just try to remove the ## at the beginning of the second line.
Also the second ## seems wrong. If you just want to initialize a singleton pointer, remove both ##s from your macro.