Can I turn this requirement into a macro? - c

I have C programs with decrementing software counters. If for instance I want to blink an led every 2 seconds I can do:
if(!ledT) {
ledT = 200;
// code
// code
// code
}
Because I always do the exact same combination with every counter, I tend to type it one line.
if(!ledT) { ledT = 200;
// code
// code
// code
}
For the entire if-line I'd like to use a macro instead. So the code would look something like:
expired(ledT, 200) {
// code
// code
// code
}
I use something similar in my state machine code for the entry state.
if(runOnce) { runOnce = false;
// code
// code
// code
Desired syntax:
entryState {
// code
// code
// code
.
#define entryState if(runOnce) { runOnce = false; // this ofcourse cannot work But something like this is what I want.
I've made several attempts but I got nowhere. The problem is that the { is somewhere in the middle of the macro and I want to type a { behind the macro because as we all know, no code editor can live with an unequal number of { and }.
expired(ledT, 200); // expired is macro, not function
// code
// code
// code
}
So this is out of the question.
Whilst reading about macros, I've read something interesting about using: do ... while(0). This 'trick' abuses the compiler's optimization feature to create a certain macro, which would otherwise be impossible.
This site
sheds some light about this manner.
Is there a way to use some kind of 'macro trick' to achieve what I want?
So again, that is transforming:
// this
if(runOnce) {
runOnce = false;
// code
// code
// code
// into this
entryState {
// code
// code
// code
// and this:
if(!someTimer) {
someTimer = someInterval;
// code
// code
// code
// must be transformed into:
timeExpired(someTimer, someInterval) {
// code
// code
// code
And an answer like "No, it simply cannot be done" will also be accepted (providing you know what you are talking about)
EDIT:
I need to add an addition because not everybody seems to know what I want, the last given answer is not even aimed at the specific problem at hand. Somehow toggling IO suddenly became important? Therfor I altered my code examples to better illustrate what the problem is.
EDIT2:
I agree that the the timeExpired macro does not improve readability at all
To show that some macros can improve readabilty I'll give a snippet of a state and a state machine. This is how a generated state looks like in my code:
State(stateName) {
entryState {
// one time only stuff
}
onState {
// continous stuff
exitFlag = true; // setting this, exits the state
}
exitState {
// one time only stuff upon exit
return true;
}
}
Currently in place with these macros:
#define State(x) static bool x##F(void)
#define entryState if(runOnce)
#define onState runOnce = false;
#define exitState if(!exitFlag) return false; else
I think I should I should exchange return true; in the states by EXIT or something prittier.
And the state machine which calls these States looks like:
#undef State
#define State(x) break; case x: if(x##F())
extern bit weatherStates(void) {
if(enabled) switch(state){
default: case weatherStatesIDLE: return true;
State(morning) {
if(random(0,1)) nextState(afternoon, 0);
else nextState(rain, 0); }
State(afternoon) {
nextState(evening, 0); }
State(evening) {
if(random(0,1)) nextState(night, 0);
else nextState(thunder, 0); }
State(night) {
nextState(morning, 0); }
State(rain) {
nextState(evening, 0); }
State(thunder) {
nextState(morning, 0); }
break; }
else if(!weatherStatesT) enabled = true;
return false; }
#undef State
The only thing which is not generated are the 'if' and 'else' before the 'nextState()' functions. These 'flow conditions' need filling in.
If a user is provided with a small example or an explanation, he should have no difficulty at all with filling in the states. He should also be able to add states manually.
I'd even like to exchange this by macros:
extern bit weatherStates(void) {
if(enabled) switch(state){
default: case weatherStatesIDLE: return true;
and
break;} }
else if(!weatherStatesT) enabled = true;
return false;}
Why would I do this? To hide irrelevant information out of your display. To remove alot of tabs in the state machine. To increase overal readability by using a simple syntax. Like with 3rd library functions you need to know how to use the code rather to know how the function does the trick.
You don't need to know, how a state signals that it is ready. It is more important to know that the function in question is used as a state function than to know that it returns a bit variable.
Also I test macros before using. So I don't provide somebody with state machines that may show strange behavior.

There’s no need to employ macros here, and doing so leads to highly un-idiomatic C code that doesn’t really have any advantages over proper C code.
Use a function instead:
int toggle_if_unset(int time, int pin, int interval) {
if (time == 0) {
time = 200;
TOG(pin);
}
return time;
}
ledT = toggle_if_unset(ledT, ledPin, 200);
(I’m guessing appropriate parameter names based on your example; adjust as appropriate.)
What’s more, it looks as if ledT and ledPin are always paired and belong together, in which case you should consider putting them into a struct:
struct led {
pin_t pin;
int interval;
};
void toggle_if_unset(struct led *led, int new_interval);
Or something along these lines.

Given that this is for some old 8051 legacy project, it is extremely unlikely that you need to create abstraction layer macros for pin I/O handling. You'll only have just so many pins. Your original code is most likely the best and clearest one.
If you for some reason worry about code repetition, because you have multiple combinations of the product/support multiple PCB with different routing etc, and you are stuck with your current code base... then as a last resort you could use macros to avoid code repetition. This also assuming that you are a seasoned C programmer - otherwise stop reading here.
What you will be looking at in that rare scenario is probably something that's known as "X macros", which is about declaring a whole list of pre-processor constants. Then whenever you need to do something repetitive, you call upon that list and use the constants inside it that you are interested for that specific call. Each call is done by specifying what the macro "X" should do in that particular call, then undefined the macro afterwards.
For example if you have ports A, B, C, you have LEDs on port A:0, B:1 and C:2 respectively and wish to use different delays per pin, you can declare a list like this:
#define LED_LIST \
/* port pin delay */ \
X(A, 0, 100) \
X(B, 1, 200) \
X(C, 2, 300) \
Then you can call upon this list when you need to do repetitive tasks. For example if these ports have data direction registers you need to set accordingly and those registers are called DDRA, DDRB, DDRC (using Motorola/AVR naming as example):
/* set data direction registers */
#define X(port, pin, delay) DDR##port |= 1u<<pin;
LED_LIST
#undef X
This will expand to:
DDRA |= 1u<<0;
DDRB |= 1u<<1;
DDRC |= 1u<<2;
Similarly, you can initialize the counters as:
/* declare counters */
#define X(port, delay) static uint16_t count##port = delay;
LED_LIST
#undef X
...
/* check if counters elapsed */
#define X(port, delay) if(count##port == 0) { count##port = delay; PORT##port ^= 1u << pin; }
LED_LIST
#undef X
(I replaced the toggle macro with a simple bitwise XOR)
Which will expand to:
static uint16_t countA = 100;
static uint16_t countB = 200;
static uint16_t countC = 300;
...
if(countA == 0)
{
countA = 100;
PORTA ^= 1u << 0;
}
if(countB == 0)
{
countB = 200;
PORTB ^= 1u << 1;
}
if(countC == 0)
{
countC = 300;
PORTC ^= 1u << 2;
}
And of course avoid using 16 bit counters like done here unless you must, since you are working with a crappy 8-bitter.

#define LL(ledT) do {if(!ledT) { ledT = 200; TOG(ledPin); }}while(0)
Whilst reading about macros, I've read something interesting about
using: do ... while(0). This 'trick' abuses the compiler's
optimization feature to create a certain macro, which would otherwise
be impossible.
Most of the opinions there are actually wrong. There is nothing about optimizations.
The main reason is to make macros using curled braces to compile at all.
This one will not compile
#define A(x) {foo(x);bar(x);}
void foo1(int x)
{
if (x) A(1);
else B(0);
}
but this one will compile
#define A(x) do{foo(x);bar(x);}while(0)
void foo1(int x)
{
if (x) A(1);
else B(0);
}
https://godbolt.org/z/4jH2jP

DISCLAIMER: I don't recommend using this solution.
I had a go at trying to make this into macro's. It is indeed possible but if it's faster, that's another question. As you make a new variable each time you call the macro.
#include <stdio.h>
#define entryState(runOnce) int temp_state = runOnce; if (runOnce) runOnce = 0; if (temp_state)
#define timeExpired(someTimer, someInterval) int temp_expired = someTimer; if (!someTimer) someTimer = someInterval; if (!temp_expired)
int main(int argc, const char* argv[]) {
int runOnce = 1;
int someTimer = 0;
int someInterval = 200;
timeExpired(someTimer, someInterval) {
printf("someTimer is Expired\n");
}
printf("someTimer: %i\n\n", someTimer);
entryState(runOnce) {
printf("this is running once\n");
}
printf("runOnce: %i\n", runOnce);
}
Compiling and running:
c:/repo $ gcc test.c -o test
c:/repo $ ./test.exe
someTimer is Expired
someTimer: 200
this is running once
runOnce: 0
I don't have a C51 compiler at hand now, so I let the testing on the 8051 over to you.

Related

using function names as functions in a C macro

Suppose i have code like this in my program:
if (!strcmp(current, "sin")) {
pushFloat(sin(x), &operands);
} else if (!strcmp(current, "cos")) {
pushFloat(cos(x), &operands);
} else if (!strcmp(current, "tan")) {
pushFloat(tan(x), &operands);
} else if (!strcmp(current, "ctg")) {
pushFloat(1. / tan(x), &operands);
} else if (!strcmp(current, "ln")) {
pushFloat(log(x), &operands);
} else if (!strcmp(current, "sqrt")) {
pushFloat(sqrt(x), &operands);
}
There are function names such as "sin" or "cos" saved in the current char array
Instead of using this long if block, or replacing it with an even longer switch block, i wanted to write a simple macro like this: #define PUSHFUNC(stack, func, value)(pushFloat(func(value), &stack)) and call it like this PUSHFUNC(operands, current, x)
Doing it this way creates an error "current is not a function or function pointer". I initially thought macros are just text replacement, so if i force a string that is equal to an actual function into a macro, it would expand to the function itself, but looks like i was wrong. Is there a way to achieve what i want using a macro, or should i just write a map block?
I initially thought macros are just text replacement,
That's your problem: macros are just text replacement. So if you have:
#define PUSHFUNC(stack, func, value) (pushFloat(func(value), &stack))
And you write:
PUSHFUNC(operands, current, x)
You get:
(pushFloat(current(value), &operands))
And indeed, you have no function named current. Macros are expanded before your code compiles; the preprocessor has no knowledge of the content of your variables.
If you really want to avoid a long chain of if statements, you could implement some sort of table lookup:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <math.h>
typedef double (*floatop)(double x);
typedef struct {
char *name;
floatop operation;
} entry;
double ctg(double);
entry opertable[] = {
{"sin", sin},
{"cos", cos},
{"tan", tan},
{"ctg", ctg},
{"sqrt", sqrt},
{NULL, NULL},
};
double ctg(double x) {
return 1. / tan(x);
}
floatop findop(char *name) {
int i;
for (i=0; opertable[i].name; i++) {
if (strcmp(opertable[i].name, name) == 0) {
return opertable[i].operation;
}
}
}
int main() {
float x = 4;
printf("sin(%f) = %f\n", x, findop("sin")(x));
printf("sqrt(%f) = %f\n", x, findop("sqrt")(x));
printf("tan(%f) = %f\n", x, findop("tan")(x));
printf("ctg(%f) = %f\n", x, findop("ctg")(x));
}
...but this requires that all of your functions take the same arguments, so for things like ctg you would need to add a helper function. You also need to decide if the increased complexity of the table lookup makes sense: it really depends on how many different operation names you expect to implement.
The output of the above code is:
sin(4.000000) = -0.756802
sqrt(4.000000) = 2.000000
tan(4.000000) = 1.157821
ctg(4.000000) = 0.863691
Is there a way to achieve what i want using a macro, or should i just write a map block?
I would recommend using an enum containing symbols for all the functions you might want to call, and using that in a switch-case block, instead of comparing a bunch of strings. Here's a very brief sample that only uses some of the functions you refer to...
enum which_func { SIN, COS, TAN, };
enum which_func which = SIN;
switch (which) {
case SIN:
pushFloat(sin(x), &operands);
break;
case COS:
pushFloat(cos(x), &operands);
break;
case TAN:
pushFloat(tan(x), &operands);
break;
default:
assert(false); // shouldn't be reachable if enum value is well-defined
}
This version will be easier to maintain in the long run, more efficient to execute and possibly more robust to logic errors (there are some compiler warnings that you can enable which will warn you if you're not handling all enum values, which can help you catch missed cases in your logic).
To add to what other answers said, what you can do is to make a macro that expands to the "basic block" of your if chain, avoiding some repetitions thanks to the stringizing operator:
#define HANDLE_FN_EXPR(fn, expr) \
else if(!strcmp(current, #fn)) \
pushFloat((expr), &operands)
#define HANDLE_FN(fn) \
HANDLE_FN_EXPR(fn, fn(x))
Then you can do
if(0);
HANDLE_FN(sin);
HANDLE_FN(cos);
HANDLE_FN(tan);
HANDLE_FN_EXPR(ctg, 1./tan(x));
HANDLE_FN(ln);
HANDLE_FN(sqrt);
Macros do in fact do text replacement. Given your macro definition, this:
PUSHFUNC(operands, current, x)
expands to this:
(pushFloat(current(x), &operands))
So as you can see, the text that is being replaced is the name of the variable, not the text that it contains.
And even if this did work as you expected, it wouldn't be able to properly handle the 1. / tan(x) case.
This means there isn't really a better way to do what you want.
Why not create some objects for each function type? I know, this is C not C++, but the idea will still work. First, create the function object type:-
typedef struct _Function
{
char *name;
float (*function) (float argument);
} Function;arg
And now create an array of function objects:-
Function functions [] =
{
{ "sin", sin },
{ "cos", cos }
// and so on
};
where the functions are defined:-
float sin(float x)
{
return 0; // put correct code here
}
float cos(float x)
{
return 0; // put correct code here
}
Finally, parse the input:-
for (int i = 0; i < sizeof functions / sizeof functions[0]; ++i)
{
if (strcmp(functions[i].name, current) == 0)
{
pushFloat(functions[i].function(arg)); // add operands!
break;
}
}
I find using enums for stuff like this very hard to maintain! Adding new functions means going through the code to find cases where the enum is used and updating it prone to errors (like missing a place!).
All because it's not C++, doesn't mean you can't use objects! It's just there's no language support for it so you have to do a bit more work (and, yeah, there are features missing!)

new preprocessor trick to me

(Below code is correct, not create by myself.)
(it is inside the config of a motor board.)
#define BTN_TABLE(X) X(BUTTON, PA1)
#define BTN_X_EXTERNS(A, B) extern Button A;
BTN_TABLE(BTN_X_EXTERNS)
#define BTN_X_ID(A, B) A##_ID
#define BTN_X_ENUM(A, B) BTN_X_ID(A, B),
typedef enum { BTN_TABLE(BTN_X_ENUM) NUM_BOARD_BUTTONS } BoardButtonID;
#define BTN_X_FROM_ENUM(A, B) else if (button_id == BTN_X_ID(A, B)) return &A;
static __forceinline Button* button_from_enum(BoardButtonID button_id) {
if (0) return 0;
BTN_TABLE(BTN_X_FROM_ENUM)
else return 0;
}
I don't get the meaning of if (0) return 0; and else return 0; in above example.
why place the Marco in between these two line?
I think we cannot place anything between if{} , else{} statement.
I think the intent behind this code was as follows:
We have some buttons; currently just one, but eventually there may be many more
Each button needs a corresponding global variable and a value in the BoardButtonID enum
We want a function which given the enum BoardButtonID value returns a pointer to the button's global variable
We want to achieve all this while only listing all buttons once.
#bolov has shown how the code expands. I'll note that one can add more buttons just by changing the definition of the BTN_TABLE macro:
#define BTN_TABLE(X) X(BUTTON, PA1) \
X(ANOTHER_BUTTON, PA2) \
X(YET_ANOTHER_BUTTON, PA3) \
X(OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP, PA4)
The PA1, PA2, ... aren't actually used in this version of the code; maybe they would have been used for something later.
Now you can see the effect (I've reformatted the output):
extern Button BUTTON;
extern Button ANOTHER_BUTTON;
extern Button YET_ANOTHER_BUTTON;
extern Button OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP;
typedef enum {
BUTTON_ID,
ANOTHER_BUTTON_ID,
YET_ANOTHER_BUTTON_ID,
OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP_ID,
NUM_BOARD_BUTTONS
} BoardButtonID;
static __forceinline Button* button_from_enum(BoardButtonID button_id) {
if (0)
return 0;
else if (button_id == BUTTON_ID)
return &BUTTON;
else if (button_id == ANOTHER_BUTTON_ID)
return &ANOTHER_BUTTON;
else if (button_id == YET_ANOTHER_BUTTON_ID)
return &YET_ANOTHER_BUTTON;
else if (button_id == OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP_ID)
return &OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP;
else
return 0;
}
And this makes it clear why the initial if is needed: the macro expansion in button_from_enum has no way to treat the first one specially. So it has to produce an else if for every button, including the first one, and the only way to make that valid is for there to be an if at the beginning. It needs to have a test that always fails, hence 0, and its corresponding "then" clause doesn't matter as it will never execute. The return 0 there may have just been chosen to shut up a compiler warning about the function possibly returning without a value. Of course, the return 0 in the final else clause can be reached, and serves as a default if someone passes a value that doesn't match any button.
You are right that if you put anything else in between the if and else, everything will break.
They could have defined it a little differently and used switch instead, which would have been slightly cleaner. I don't know why they didn't; maybe the compiler generates different code that they didn't like (e.g. a jump table that occupies more code space).
In any event, the resulting set of macros, while clever, are certainly not very easy to maintain. They should probably have considered writing a script instead that would generate the desired code from a simple list of buttons in a text file.
Or, they could have put the Button objects in an array instead of insisting on each one having its own variable. This would go nicely with their enum:
typedef enum {
BUTTON_ID,
ANOTHER_BUTTON_ID,
YET_ANOTHER_BUTTON_ID,
OH_GOD_NOT_ANOTHER_BUTTON_MAKE_THEM_STOP_ID,
NUM_BOARD_BUTTONS
} BoardButtonID;
Button all_the_buttons[NUM_BOARD_BUTTONS];
static __forceinline Button* button_from_enum(BoardButtonID button_id) {
if (button_id < NUM_BOARD_BUTTONS)
return &all_the_buttons[button_id];
else
return NULL;
}
This way still only requires listing the buttons once, and it involves no macros at all.
This is one of the most unreadable pieces of code I have seen.
I personally don't have neither the time, energy or willingness to analyze and figure out these horible macros. So I just dumped the preprocessor output and this is the code presented to the compiler:
extern Button BUTTON;
typedef enum { BUTTON_ID, NUM_BOARD_BUTTONS } BoardButtonID;
static __forceinline Button* button_from_enum(BoardButtonID button_id) {
if (0) return 0;
else if (button_id == BUTTON_ID) return &BUTTON;
else return 0;
}
it is inside the config of a motor board.
That explains the code. It is consistent with code that is generated by other software, rather than by a human. It is generated by some code that configures a software package to some target environment.
The purpose of code like this:
if (0) return 0;
BTN_TABLE(BTN_X_FROM_ENUM)
else return 0;
is to allow the generating code to put any number of else if lines between the if line and the else line. For example, in various circumstances, the generated code might be this:
if (0) return 0;
else return 0;
or this:
if (0) return 0;
BTN_TABLE(BTN_X_FROM_ENUM)
else return 0;
or this:
if (0) return 0;
BTN_TABLE(BTN_X_FROM_ENUM)
BTN_TABLE(BTN_Y_FROM_ENUM)
else return 0;
By using if (0) and else as bookends, the generating code is freed from having to have conditional cases such as “If there are zero conditions, just write return 0;. If there is one condition, write if (condition) return something; else return 0;. If there are multiple conditions, write if (first condition) return something; else if (second condition) return something;… else return 0;.
Instead, the generating code is simply:
Write if (0) return 0;.
For each condition, write an else if line for it (likely in the form of some BTN_TABLE macro use, the definition for which is emitted elsewhere in the generating code).
Write else return 0;.
Thus, while the resulting code is more complicated, the actual generating code is simpler.
I don't get the meaning of if (0) return 0; and else return 0; in above example.
The if (0) is needed simply so that the following lines can be any number of else if statements. The return 0; is never executed and is simply needed to complete the if statement grammatically.
The else return 0; statement provides a default in case none of the conditions are met.
why place the Marco in between these two line?
The generating code emits a macro invocation for every case it determines is needed in the target system.
I think we cannot place anything between if{} , else{} statement.
Of course you can, the else if statements are proper there.

"resettable" loop DSL with C macros?

I want a loop to run once unless set to repeat, but I don't like the ugliness of having to explicitly set variables as part of normal program flow.
I'm using this but the project maintainers didn't like it:
int ok = 0;
while (ok^=1) {
// ...
if (something_failed) ok = 0;
}
(compare to while (!ok) { ok = 1; // ...)
The nice thing is that you can wrap these in macros:
#define RETRY(x) while (x^=1)
#define FAIL(x) x = 0
and use them as
int ok = 0;
RETRY(ok) {
// ...
if (something_failed) FAIL(ok);
}
How can I make these macros work without the weird xor-assign?
Using XOR 1 to toggle something between 0 and 1 repeatedly is perfectly fine, particularly in hardware-related code. Is this what you are trying to do? But this isn't how you are using it, so it doesn't make sense. Also, using it together with a signed int is questionable.
Please don't invent some ugly macro language, that's 10 times worse! This is the worst thing you can do.
There exists no reason why you can't simply do something along the lines of this:
bool retry = true;
while(retry)
{
retry = false;
...
if(something_failed) retry = true;
}

Portable instrumentation

GCC has a nice feature about instrumentation which let you call a routine every time a function is called, or every time a function returns.
Now, I want to create my own system to make it portable to other compilers, and also to allow to instrumentalize the functions I want (which can vary in number of parameters), so I was thinking in two macro for both situations. I am thinking in making some kind of profile that it is activated only with a define clause.
#define FUNCT(t,function_name,...) \
(t) function_name(...) { \
(void) *func_pointer = &(function_name); \
start_data(func_pointer, myclock());
#define RETURN(x) {stop_data(func_pointer, myclock()); return (x);}
FUNCT(BOOL, LMP, const int prof, const int nmo))
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
RETURN(FALSE);
}
... do more....
RETURN(TRUE);
}
but I can’t get it to work. Can someone help me with this? or is this a difficult task to accomplish?
Other alternative that comes to my mind is let the function declare without a macro, and if it is anyway to know the function pointer without knowing its name, something like in VB when you call a Form with Me, with it is a generic alias. is it possible?
Use gcc -E to debug your macros. Using the code you posted:
$ gcc -E t.c
# ... skip stuff ....
(BOOL) LMP(...) { (void) *func_pointer = &(LMP);
start_data(func_pointer, myclock());)
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
{stop_data(func_pointer, myclock()); return (FALSE);};
}
... do more....
{stop_data(func_pointer, myclock()); return (TRUE);};
}
(I added some whitespace to make it readable.)
You can see two problems immediately: function arguments didn't get expanded as you thought they would, and there's an extra ) from somewhere.
To get the expanded variadic arguments, use __VA_ARGS__, not .... The stray ) is at the call site.
So:
#define FUNCT(t,function_name,...) \
(t) function_name(__VA_ARGS__) { \
(void) *func_pointer = &(function_name); \
start_data(func_pointer, myclock());
#define RETURN(x) {stop_data(func_pointer, myclock()); return (x);}
FUNCT(BOOL, LMP, const int prof, const int nmo)
if (nmo <= 5 ||
prof > (prof_l / 3)) {
.... do long operations....
RETURN(FALSE);
}
... do more....
RETURN(TRUE);
}
As to whether this is worth trying (variadic macros came with C99, not all compilers implement that standard, and support might vary from compiler to compiler), I'm not certain. You are probably better off using each compiler's native profiling tools - you'll get better results with hopefully less overhead.
It is much easier to instrument your functions at the calling side instead of the function side. A macro can have the same name as a function. Declare your replacement function somewhere
double myfunc_wrapper(int someArg) {
double ret = 0;
// do something before
...
// now call it
ret = (myfunc)(someArg);
// Then do something after
....
return ret;
}
Just to be sure put the () arround the call itself to be sure that always a function is called and not a macro.
And then "overload" your function with a macro
#define myfunc(...) mfunc_wrapper(__VA_ARGS__)
with that idea you can replace your function on the fly in the compilation units that interes you.
in addition to Mat, there is a ergonimical problem with using #define RETURN(x) {...}:
if (test)
RETURN (TRUE);
else
RETURN (FALSE);
will evaluate to
if (test)
{...}
; // <syntactical error
else
{...}
;

Macro questions

On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.
Has somebody a idea how i can make a macro like that?
SET(SomeVariable, 137);
which will execute
SomeVariable = 137;
SomeVariable_inverse = ~137;
Edit:
The best Solution seems to be:
#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
Thanks for the answers
Try this
#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
EDIT
Couple of links to the reason behind adding a do/while into the macro
https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for
http://www.rtems.com/ml/rtems-users/2001/august/msg00111.html
http://c2.com/cgi/wiki?TrivialDoWhileLoop
http://blogs.msdn.com/jaredpar/archive/2008/05/21/do-while-0-what.aspx
One hazard I haven't seen mentioned is that the 'value' macro argument is evaluated twice in most of the solutions. That can cause problems if someone tries something like this:
int x = 10;
SET(myVariable, x++);
After this call, myVariable would be 10 and myVariable_inverse would be ~11. Oops. A minor change to JaredPar's solution solves this:
#define SET(var,value) do { var = (value); var##_inverse = ~(var); } while(0)
Why are you storing the inverse when it can be so easily calculated? This seems like a bad idea to me.
You can do it in a single statement, which avoids having to use do {} while (0).
#define SetInverse(token, value) (token##_inverse = ~(token = (value)))
Also, this only evalutes (value) once, which is always nice.
#define SetInverse(token, value) { token = value; token##_inverse = ~value; }
Jinx, Jared - like the while (0) in yours
Just to offer an alternative method:
Store each variable as a structure like this:
typedef struct
{
u32 u32Normal;
u32 u32Inverted;
} SafeU32TYPE
Then have a function which takes a pointer to one of these, along with the value to be set, and stores that value with its inverse:
void Set(SafeU32TYPE *pSafeU32, u32Data)
{
if(pSafeU32 != NULL)
{
pSafeU32->u32Normal = u32Data;
pSageU32->u32Inverted = ~u32Data;
} /* if */
} /* Set() */
Advantage: if you need the set function to do something more powerful, such as boundary checking, or storing in some more complex way, then it can be easily extended.
Disadvantage: you'll need a different function for each type used, and if processor resource is an issue, this is less efficient than using a macro.

Resources