Getting a string of class variable via macro? - c++

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"

Related

multiple lines macro in C

does anyone know why this is syntactically wrong?
Im trying to covert this
#define OUTS_FROM_FP(_fp, _argCount) ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
to this
#define OUTS_FROM_FP(_fp, _argCount) {\
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
}
outs = OUTS_FROM_FP(fp, vsrc1); --this is how it is being called
I get a lot of errors when running this: they start from statements that say that variables that were passed to the macro before are unused
Expanded, the original macro will look like this:
outs = ((u4*) ((u1*)SAVEAREA_FROM_FP(fp) - sizeof(u4) * (vsrc)));
That's (as far as I can tell as you didn't provide much context) valid code.
Your modified macro expands the same statement to this:
outs = { /* ... */ };
Your compiler gets all kinds of confused as you are attempting to assign a code block to a variable...
All the usual caveats regarding the use of macros in general aside, you could use the comma operator to get your modified macro "working":
#define OUTS_FROM_FP( _fp, _argCount ) \
cout << "Hello world\n", \
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
(The output is put first, as statements separated by the comma operator evaluate to the result of the last statement -- putting the output first makes the macro still evaluate to the same value as the original macro.)
All in all, you're probably better off turning that macro into a function.
Assuming that _fp and _argCount are variables or simple expressions, the original version is an expression of type u4*.
The second is more complicated. The braces make it a block, but syntactically you’re using it as an expression. This is not allowed in the C++ standard, but is supported by g++ and some other compilers. Since you say you’re using GCC, the value of this expression is the value of the last line of the block, which in this case is cout<<"Hello World"<<endl. If you were using a compiler which did not support statement expressions, you’d get a more confused syntax error.
I expect that unless you can convert an ostream to a u4 pointer (which, given what context we have, seems very unlikely), this won’t work. In this simple case, you can fix it by simply switching the order of the lines in the block. In a more complicated case, which I expect is the end goal, you probably would need to do something like
#define OUTS_FROM_FP(_fp, _argCount) {\
u4* result = ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
result; \
}
This saves the output of the macro to a temporary variable, does whatever calculations you want (which can change result), and then on the last line “returns” result outside the macro. This is less portable than DevSolar’s solution, but it works better if you need to create temporary variables, and in my opinion is more readable.
However, as others point out in the comments, there is little reason (at least that we can see) to keep this as a macro instead of converting it to a function. Functions are much more robust in a variety of ways. Reasons you might still want to keep it as a macro include the definition of SAVEAREA_FROM_FP changing or the types u4 and u1 being different in different places. Neither of these would not be good programming practice, but you can’t control what others have done before and I don’t know enough about Dalvik to say it isn’t the case.

Macro that calls different function based on parameter

Hello all I was having trouble with macros so I thought I would practice and I was looking at the ## macro operator and thought I could use it for my problem I wan't to be able to call multiple functions based on the parameter for example if I have a macro like so:
#define macro(a) func##a();
int main()
{
.....
for(int i = 0;i< length;i++)
{
macro(i)
}
func1()
{
}
....
func31()
{
}
Anyone have an idea of how I can accomplish this??
You can only combine two preprocessor tokens. However, func isn't a preprocessor token. You need to jump through an extra hoop, calling some form of "concat" macro:
#define CONCAT(a, b) a ## b
#define macro(a) CONCAT(func,a)
Of course, the tokens produced by you macro won't be func1, ..., func31 (of course, they would also need to start with func0 if your logic were correct) but rather funci. The expansion of macros happens at the beginning of compilation while the execution of the for-loop happens at run-time (some optimizations may hoist it into compile-time but that won't affect the macros).
If you need to expand a sequence of integers in combination with a macro, you may want to have a look at the Boost preprocessor library, in particular at the BOOST_PP_REPEAT functionality.
If you just need to statically expand a sequence of integers to function calls, you might also consider looking at function template templatized on an integers: I would certainly consider using an approach using templates before trying to use the preprocessor library...

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.

What does "#define STR(a) #a" do?

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"

C++ Preprocessor metaprogramming: obtaining an unique value?

I'm exploiting the behavior of the constructors of C++ global variables to run code at startup in a simple manner. It's a very easy concept but a little difficult to explain so let me just paste the code:
struct _LuaVariableRegistration
{
template<class T>
_LuaVariableRegistration(const char* lua_name, const T& c_name) {
/* ... This code will be ran at startup; it temporarily saves lua_name and c_name in a std::map and when Lua is loaded it will register all temporarily global variables in Lua. */
}
};
However manually instantiating that super ugly class every time one wants to register a Lua global variable is cumbersome; that's why I created the following macro:
#define LUA_GLOBAL(lua_name, c_name) static Snow::_LuaVariableRegistration _____LuaGlobal ## c_name (lua_name, c_name);
So all you have to do is put that in the global scope of a cpp file and everything works perfectly:
LUA_GLOBAL("LuaIsCool", true);
There you go! Now in Lua LuaIsCool will be a variable initialized to true!
But, here is the problem:
LUA_GLOBAL("ACCESS_NONE", Access::None);
Which becomes:
static Snow::_LuaVariableRegistration _____LuaGlobalAccess::None ("ACCESS_NONE", &Access::None);
:((
I need to concatenate c_name in the macro or it will complain about two variables with the same name; I tried replacing it with __LINE__ but it actually becomes _____LuaGlobalAccess__LINE__ (ie it doesn't get replaced).
So, is there a way to somehow obtain an unique string, or any other workaround?
PS: Yes I know names that begin with _ are reserved; I use them anyway for purposes like this being careful to pick names that the standard library is extremely unlikely to ever use. Additionally they are in a namespace.
You need to add an extra layer of macros to make the preprocessor do the right thing:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ...
Some compilers also support the __COUNTER__ macro, which expands to a new, unique integer every time it is evaluated, so you can use that in place of __LINE__ to generate unique identifiers. I'm not sure if it's valid ISO C, although gcc accepts its use with the -ansi -pedantic options.