Has Anyone Ever Had a Use for the _Counter_ Pre-Processor MACro

Has anyone ever had a use for the __COUNTER__ pre-processor macro?

It's used in the xCover code coverage library, to mark the lines that execution passes through, to find ones that are not covered.

C Preprocessor: Own implementation for __COUNTER__

You can't implement __COUNTER__ directly. The preprocessor is purely functional - no state changes. A hidden counter is inherently impossible in such a system. (BOOST_PP_COUNTER does not prove what you want can be done - it relies on #include and is therefore one-per-line only - may as well use __LINE__. That said, the implementation is brilliant, you should read it anyway.)

What you can do is refactor your metaprogram so that the counter could be applied to the input data by a pure function. e.g. using good ol' Order:

#include <order/interpreter.h>

#define ORDER_PP_DEF_8map_count \
ORDER_PP_FN(8fn(8L, 8rec_mc(8L, 8nil, 0)))

#define ORDER_PP_DEF_8rec_mc \
ORDER_PP_FN(8fn(8L, 8R, 8C, \
8if(8is_nil(8L), \
8R, \
8let((8H, 8seq_head(8L)) \
(8T, 8seq_tail(8L)) \
(8D, 8plus(8C, 1)), \
8if(8is_seq(8H), \
8rec_mc(8T, 8seq_append(8R, 8seq_take(1, 8L)), 8C), \
8rec_mc(8T, 8seq_append(8R, 8seq(8C)), 8D) )))))

ORDER_PP (
8map_count(8seq( 8seq(8(A)), 8true, 8seq(8(C)), 8true, 8true )) //((A))(0)((C))(1)(2)
)

(recurses down the list, leaving sublist elements where they are and replacing non-list elements - represented by 8false - with an incrementing counter variable)

I assume you don't actually want to simply drop __COUNTER__ values at the program toplevel, so if you can place the code into which you need to weave __COUNTER__ values inside a wrapper macro that splits it into some kind of sequence or list, you can then feed the list to a pure function similar to the example.

Of course a metaprogramming library capable of expressing such code is going to be significantly less portable and maintainable than __COUNTER__ anyway. __COUNTER__ is supported by Intel, GCC, Clang and MSVC. (not everyone, e.g. pcc doesn't have it, but does anyone even use that?) Arguably if you demonstrate the feature in use in real code, it makes a stronger case to the standardisation committee that __COUNTER__ should become part of the next C standard.

Preprocessor counter macro

GCC, and (I believe) VC++ both provide the __COUNTER__ macro, which does about what you'd expect. I don't know that it follows the standard exactly, but it's probably close enough for real-world use.

What is the worst real-world macros/pre-processor abuse you've ever come across?

From memory, it looked something like this:

#define RETURN(result) return (result);}

int myfunction1(args) {
int x = 0;
// do something
RETURN(x)

int myfunction2(args) {
int y = 0;
// do something
RETURN(y)

int myfunction3(args) {
int z = 0;
// do something
RETURN(z)

Yes that's right, no closing braces in any of the functions. Syntax highlighting was a mess, so he used vi to edit (not vim, it has syntax coloring!)

He was a Russian programmer who had mostly worked in assembly language. He was fanatical about saving as many bytes as possible because he had previously worked on systems with very limited memory. "It was for satellite. Only very few byte, so we use each byte over for many things." (bit fiddling, reusing machine instruction bytes for their numeric values) When I tried to find out what kinds of satellites, I was only able to get "Orbiting satellite. For making to orbit."

He had two other quirks: A convex mirror mounted above his monitor "For knowing who is watching", and an occasional sudden exit from his chair to do a quick ten pushups. He explained this last one as "Compiler found error in code. This is punishment".

__COUNTER__ macro problems. Not displaying the value

You have to expand the macro:

#define MACRO3(s) ht##s
#define MACRO2(s) MACRO3(s)
#define MACRO MACRO2(__COUNTER__)

int MACRO ; //ht0
int MACRO ; //ht1

C++ __COUNTER__ Definition

__COUNTER__ is a built-in in several common compilers. It is not possible to define manually. If you're stuck with a compiler that doesn't support it, your best option might be to run your code through a preprocessor that does support it before feeding it into the compiler.

Incrementing Preprocessor Macros

The "problem" is that macros are lazily evaluated. Consider your macro definition:

#define PREPROCESSOR_LOOP_ITERATION (PREPROCESSOR_LOOP_ITERATION + 1)

This defines a macro named PREPROCESSOR_LOOP_ITERATION and its replacement list is the sequence of five preprocessing tokens (, PREPROCESSOR_LOOP_ITERATION, +, 1, and ). The macro is not expanded in the replacement list when the macro is defined. Macro replacement only takes place when you invoke the macro. Consider a simpler example:

#define A X
#define B A

B // this expands to the token X

#undef A
#define A Y
B // this expands to the token Y

There is an additional rule that if the name of a macro being replaced is encountered in a replacement list, it is not treated as a macro and thus is not replaced (this effectively prohibits recursion during macro replacement). So, in your case, any time you invoke the PREPROCESSOR_LOOP_ITERATION macro, it gets replaced with

( PREPROCESSOR_LOOP_ITERATION + 1 )

then macro replacement stops and preprocessing continues with the next token.

You can perform limited arithmetic with the preprocessor by defining a sequence of macros and making use of the concatenation (##) operator, but it's quite tedious. You should consider using the Boost.Preprocessor library to help you with this. It will work with both C and C++ code. It allows for limited iteration, but what it does allow is extraordinarily useful. The closest feature that matches your use case is likely BOOST_PP_ITERATE. Other facilities like the sequence (BOOST_PP_SEQ) handlers are very helpful for writing generative code.

What is the worst real-world macros/pre-processor abuse you've ever come across?

From memory, it looked something like this:

#define RETURN(result) return (result);}

int myfunction1(args) {
int x = 0;
// do something
RETURN(x)

int myfunction2(args) {
int y = 0;
// do something
RETURN(y)

int myfunction3(args) {
int z = 0;
// do something
RETURN(z)

Yes that's right, no closing braces in any of the functions. Syntax highlighting was a mess, so he used vi to edit (not vim, it has syntax coloring!)

He was a Russian programmer who had mostly worked in assembly language. He was fanatical about saving as many bytes as possible because he had previously worked on systems with very limited memory. "It was for satellite. Only very few byte, so we use each byte over for many things." (bit fiddling, reusing machine instruction bytes for their numeric values) When I tried to find out what kinds of satellites, I was only able to get "Orbiting satellite. For making to orbit."

He had two other quirks: A convex mirror mounted above his monitor "For knowing who is watching", and an occasional sudden exit from his chair to do a quick ten pushups. He explained this last one as "Compiler found error in code. This is punishment".

Why are preprocessor macros evil and what are the alternatives?

Macros are just like any other tool - a hammer used in a murder is not evil because it's a hammer. It is evil in the way the person uses it in that way. If you want to hammer in nails, a hammer is a perfect tool.

There are a few aspects to macros that make them "bad" (I'll expand on each later, and suggest alternatives):

  1. You can not debug macros.
  2. Macro expansion can lead to strange side effects.
  3. Macros have no "namespace", so if you have a macro that clashes with a name used elsewhere, you get macro replacements where you didn't want it, and this usually leads to strange error messages.
  4. Macros may affect things you don't realize.

So let's expand a little here:

1) Macros can't be debugged.
When you have a macro that translates to a number or a string, the source code will have the macro name, and many debuggers can't "see" what the macro translates to. So you don't actually know what is going on.

Replacement: Use enum or const T

For "function-like" macros, because the debugger works on a "per source line where you are" level, your macro will act like a single statement, no matter if it's one statement or a hundred. Makes it hard to figure out what is going on.

Replacement: Use functions - inline if it needs to be "fast" (but beware that too much inline is not a good thing)

2) Macro expansions can have strange side effects.

The famous one is #define SQUARE(x) ((x) * (x)) and the use x2 = SQUARE(x++). That leads to x2 = (x++) * (x++);, which, even if it was valid code [1], would almost certainly not be what the programmer wanted. If it was a function, it would be fine to do x++, and x would only increment once.

Another example is "if else" in macros, say we have this:

#define safe_divide(res, x, y)   if (y != 0) res = x/y;

and then

if (something) safe_divide(b, a, x);
else printf("Something is not set...");

It actually becomes completely the wrong thing....

Replacement: real functions.

3) Macros have no namespace

If we have a macro:

#define begin() x = 0

and we have some code in C++ that uses begin:

std::vector<int> v;

... stuff is loaded into v ...

for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;

Now, what error message do you think you get, and where do you look for an error [assuming you have completely forgotten - or didn't even know about - the begin macro that lives in some header file that someone else wrote? [and even more fun if you included that macro before the include - you'd be drowning in strange errors that makes absolutely no sense when you look at the code itself.

Replacement: Well there isn't so much as a replacement as a "rule" - only use uppercase names for macros, and never use all uppercase names for other things.

4) Macros have effects you don't realize

Take this function:

#define begin() x = 0
#define end() x = 17
... a few thousand lines of stuff here ...
void dostuff()
{
int x = 7;

begin();

... more code using x ...

printf("x=%d\n", x);

end();

}

Now, without looking at the macro, you would think that begin is a function, which shouldn't affect x.

This sort of thing, and I've seen much more complex examples, can REALLY mess up your day!

Replacement: Either don't use a macro to set x, or pass x in as an argument.

There are times when using macros is definitely beneficial. One example is to wrap a function with macros to pass on file/line information:

#define malloc(x) my_debug_malloc(x, __FILE__, __LINE__)
#define free(x) my_debug_free(x, __FILE__, __LINE__)

Now we can use my_debug_malloc as the regular malloc in the code, but it has extra arguments, so when it comes to the end and we scan the "which memory elements hasn't been freed", we can print where the allocation was made so the programmer can track down the leak.

[1] It is undefined behaviour to update one variable more than once "in a sequence point". A sequence point is not exactly the same as a statement, but for most intents and purposes, that's what we should consider it as. So doing x++ * x++ will update x twice, which is undefined and will probably lead to different values on different systems, and different outcome value in x as well.



Related Topics



Leave a reply



Submit