#define (CLASS) in c++ - c++

I was looking at some coding done in a header file of a program installed on my PC & i found this :
# define A( CLASS ) \
B(CLASS) \
void *D(const C*to);
can anybody tell me what this means?
what are those slashes for & why hasnt all of this written in 1 line?
what does (CLASS) mean over here?
& why is there so much spacing done?

The \ just append the statements on two different lines.
It is essential same as:
#define A(CLASS) B(CLASS) void *D(const C*to);
This is done probably just for better readability.

The backslashes are there to "protect" the newline -- the preprocessor will throw away both the \ and the newline when reading in the file, putting the entire thing on one logical line. (Well, it'll also emit #line markups so the compiler can generate decent error messages too.)
Someone thought that layout was more legible than this:
#define A(CLASS) B(CLASS) void *D(const C*to);
If you imagine that B, D, and C are probably replaced with something else in the file, it'll look a bit like this in the output:
Monkey(Simian) void *Bananas(const sticks *to);
It must have made more sense to them, as they wrote the macro, to instead "see" it like this:
Monkey(Simian)
void *Bananas(const sticks *to);
I'm not sure it is an improvement (and I think I hate the style), but hopefully it makes sense now.

The slashes \ means the definition of the macro continues on the next line. In the absense of \, the next line would not be considered as a part of the macro, because by default macro considers only one line on which #define is written.
It is analogous to [contd...] which many people often use in English language (especially on online forums), to indicate continuation.

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.

How to write safe and user friendly c/c++ #define macros

I have been thinking about how macros can be written to be safe, readable and intuitive. Proper use of them should be understood by the looks of them and when used incorrectly the compiler should tell you, and not let you introduce an obscure bug.
When writing multiple line define macros I usually find myself constructing them like this to fullfill the desired criteria:
#define macro(x) do{ \
... some code line ; \
... some code line ; \
}while(0)
This way you can both...
if (a)
{
macro(a);
}
and...
if (a)
macro(a);
else
{
...
}
A nice feature of this is that if you use them incorrectly you will get a compiler error. This will not compile for example:
if (a)
macro(a)
else
b();
However, I have seen SW developers read this kind of macro construct and getting quite perplexed by it. Can you think of alternative ways to write macros that will not deceive the user in a way where they do something other than expected, and still are quite understandable when browsing a new piece of code?
Also, can you find any problems with the do {} while(0) method? It could for example be a situation where you would expect the macro to behave a certain way and where this is not the case.
The reason why i am not completely convinced the do {} while(0) method is good practice is that the macros themselves look a bit weird and take some explaining to anyone (some at least) who has not seen the construct before.
Edit:
Here is an example from one of the links in the comments (thanks!) that i like. It's quite readable I think:
#define MYMACRO(a,b) \
if (xyzzy) asdf(); \
else (void)0
Is it possible to break it?
A common approach when you want your macro to do nothing, and toggle this behavior with the preprocessor, is to use the void(0) operation.
#if SOMETHINGS
#define macro(x) do{ \
... some code line ; \
... some code line ; \
}while(0)
#else
#define macro(x) ((void)(0))
#endif
This way you won't break compilation whenever nulling out macro operations

Converting string value in a preprocessor

I need to convert an expression to its result before applying it on a preprocessor. This is probably a simple problem, but I couldn't figure out a way to do it.
My preprocessor is like this:
#define ABCD(BITPOS) \
if(BIT##BITPOS##_MASK & 0x01) { \
Do something; }
And BIT0_MASK to BIT100_MASK is defined at some place.
If I call ABCD(5), preprocessor converts it to BIT5_MASK and it works fine.
But, I want to call it like this:
ABCD(START_VAL+2),
it gives me compilation error saying BITSTART_VAL is not declared, )_MASK is not defined and whole bunch of related errors.
How can I make it work ? Appreciate your responses.
The preprocessor macro system cannot evaluate arithmetic operators. It can only splice tokens together and substitute identifiers.
You will need to find another solution.
If you really really must do this, the folks at Boost created macros to perform some basic arithmetic, using only splicing and substitution as a basis. That is not an appropriate tool for this job, though.
Looks like you need an inline function rather than a macro.
inline size_t ABCD(unsigned int bitmask)
{
if (bitmask & 0x01U)
{
something();
}
}
The inline keyword will hint to the compiler that you want the code to be pasted rather than called.

Defining a Preprocessor Macro

I'm relatively new to C++ and I'm taking a class on it. Our class was assigned a lab and my teacher has said that the lab write-up is a bit hard to understand; however, he did not make any changes to the lab write-up. So, I came across this part of the lab:
Defining a Preprocessor Macro
Long-standing convention capitalizes macro names, and this macro name must be TRACE_FUNC. The macro has a single parameter, a symbol that will be replaced by a function name when you apply the macro to the code. The start of the macro looks like this:
#define TRACE_FUNC( symbol ) replacement-text`
and the preprocessor will substitute the replacement text everywhere that the TRACE_FUNC( sym ) string exists in the source code, AND feed the symbol into that replacement.
NOTE: the #define statement must be all on a single, logical line. To keep the length manageable, you can escape the newline character with a backslash at the end of the line; that will keep the preprocessor happy while allowing you to span a definition across multiple lines.
For this exercise, the replacement text must be a complete statement, including the terminating semi-colon.
The replacement text must be an output statement that prints the symbol followed by the text () called. and a newline to standard output. You can copy and modify one of the output statements from the warning.cpp source file.
warning.cpp is just a file we're using and TRACE_FUNC is being placed in a header file.
So, I read this a couple times and I'm not 100% sure what it's asking. Looking at it one way, it seems like it's asking me to create a macro called TRACE_FUNC. If you look at it another way, it's asking me to use the macro TRACE_FUNC. All of that is fine, but I don't know how to use TRACE_FUNC at all, I can't find any documentation on it anywhere and I don't know how to create a macro. When I asked for help, my teacher just kind of said. words and not ones that were very helpful because it was a very winding, confusing answer with no explanation of what TRACE_FUNC actually is.
Basically, all that my teacher said was that the symbol within TRACE_FUNC needs to be the name of one of the functions in the source code. As an example, say we had a function foo() within warning, then the symbol is supposed to be foo() (or foo, I'm not sure of that, either), from his explanation. Also, in the replacement text, apparently the name itself will be replaced if I put # in front of the symbol. I thought that supposed to denote preprocessor directives. Why am I supposed to be using it here?
Anyway, doing what my teacher says pretty much does nothing. Neither this line
#define TRACE_FUNC( foo() ) #foo() called. ;
nor this line
#define TRACE_FUNC( foo ) #foo () called. ;
replace any text, which I'm pretty sure is the operation of the #define directive. So I must be applying what my teacher said in the wrong way, but I don't really know why it's wrong or how to fix it.
So, my question. Is TRACE_FUNC actually a macro and if so, is there any documentation on it that I can read? Or am I supposed to be creating TRACE_FUNC and if so, how exactly am I supposed to do that?
Wow, what utter rubbish! You're supposed to be learning C++ right, not intricacies of the preprocessor.
Here's what you are supposed to be doing, though why is anyone's guess.
#define TRACE_FUNC(sym) std::cout << #sym << "() called\n"
void foo()
{
TRACE_FUNC(foo);
...
}
I'm assuming that there are examples from warning.cpp that use std::cout if not then you'll have to adapt the above to whatever you find in warning.cpp.
The idea is that each function starts with a use of the TRACE_FUNC macro, so you can trace the execution of your code. Why the professor thinks this is a good idea for newbies is beyond me. Even if it were a good idea, that you are expected to figure out the details for yourself is even stupider.
I could improve the macro above but that would probably confuse even more so I won't. For now I would just do what the professor says but ignore it. Hopefully he'll get onto stuff that's worth learning later.
here is a example: use the ouput print function in your libray to replace the standard function printf here
#define TRACE_FUNC(sym) printf("%s() called", #sym);
to use it as
TRACE_FUNC(printf)
the output should be
printf() called
your actual task is to print out a symbol in a defined format. so you need printf or similar function in your #define.

Any utility to test expand C/C++ #define macros?

It seems I often spend way too much time trying to get a #define macro to do exactly what i want. I'll post my current dilemma below and any help is appreciated. But really the bigger question is whether there is any utility someone could recommend, to quickly display what a macro is actually doing? It seems like even the slow trial and error process would go much faster if I could see what is wrong.
Currently, I'm dynamically loading a long list of functions from a DLL I made. The way I've set things up, the function pointers have the same nanes as the exported functions, and the typedef(s) used to prototype them have the same names, but with a prepended underscore. So I want to use a define to simplify assignments of a long long list of function pointers.
For example, In the code statement below, 'hexdump' is the name of a typedef'd function point, and is also the name of the function, while _hexdump is the name of the typedef. If GetProcAddress() fails, a failure counter in incremented.
if (!(hexdump = (_hexdump)GetProcAddress(h, "hexdump"))) --iFail;
So let's say I'd like to replace each line like the above with a macro, like this...
GETADDR_FOR(hexdump )
Well this is the best I've come up with so far. It doesn't work (my // comment is just to prevent text formatting in the message)...
// #define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/""))) --iFail;
And again, while I'd APPRECIATE an insight into what silly mistake I've made, it would make my day to have a utility that would show me the error of my ways, by simply plugging in my macro.
Go to https://godbolt.org/. Enter your code in the left pane and select compiler as gcc put the argument as -E in the right pane. Your pre-processed code will appear on the right.
You can just run your code through the preprocessor, which will show you what it will be expanded into (or spit out errors as necessary):
$ cat a.c
#define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/"")))
GETADDR_FOR(hexdump)
$ gcc -E a.c
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.c"
a.c:1:36: error: '#' is not followed by a macro parameter
GETADDR_FOR(hexdump)
In GCC, it's gcc -E foo.c to only preprocess the file.
Visual Studio uses the /P argument.
http://visualstudiogallery.msdn.microsoft.com/59a2438f-ba4a-4945-a407-a1a295598088 - visual studio plugin to expand macroses
You appear to be confused about what the exact syntax is for stringifying or token pasting in C preprocessor macros.
You might find this page about C preprocessor macros in general helpful.
In particular, I think this macro should read like this:
#define GETADDR_FOR(a) if (!(a = (_##a)GetProcAddress(h, #a))) --iFail
The trailing ; should be skipped because you will likely be typing this as GETADDR_FOR(hexdump);, and if you don't it will look very strange in your C code and confuse many syntax highlighters.
And as someone else mentioned gcc -E will run the preprocessor and skip the other compilation steps. This is useful for debugging preprocessor problems.
You might want to take a look at Boost Wave. Like most of Boost, it's really more a library than a utility, but it does have a driver to act as a complete preprocessor.