goto label trick in a macro for condition - c

There was one evil macro trick I DON'T REMEMBER and it was a lot like this:
public :
var = 3;
}
Which should expand to
if(route == ROOTING_PUBLIC)
{
var = 3;
}
How can I achieve something like this ?

Macros are used to reduce clutter; though a lot of clutter indicates problems with the program structure.
The OP's notion of the possible macro does not match C-syntax. But something along those lines might be:
#define if_ROOTED(name) if (ROOTED_##name & input) { output = e##name; }
#define ROOTED_FIRST 16
#define ROOTED_SECOND 64
#define eFIRST 1
#define eSECOND 2
if_ROOTED(FIRST);
if_ROOTED(SECOND);
where input and output and the repetitive test are the "clutter" to be eliminated. Making a table would be a better way to reduce clutter; however OP asked for a hint about macros.

Now that I found the implementation of such bad idea, I also could understand the deeper sense in it.
The code
#define public if(route == ROOTING_PUBLIC) { public_offset
The usage
public :
var = 3;
} // <-- makes no sense
The idea
To avoid loops, to reduce the spaghetti code and to demonstrate more exotic code. It will be better to be implemented with an id system as such:
#define public(id) if(route == ROOTING_PUBLIC) { public_##id
And then if the user decides to loop the code (that by semantics will be invoked solely "publicly"):
public(2) :
var = 3;
if(var > 3) goto public_2; // or #define repeat(x, id) goto x##_##id
}
Even better version of it will include the omitting of magic numbers, replacing it with user_id

Related

"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;
}

Array of macros in c -- is it possible

I was wondering if it is possible to create something like an array of macros.
I've implemented the following code which works:
struct led_cmds_
{
ioport_pin_t *commands[LED_COUNT] ;
};
struct led_cmds_ the_led_cmd_ ;
void populate() {
the_led_cmd_.commands[0] = SPECIFICPIN(0);
}
and in main:
int main(void)
{
//.....
populate();
LED_On(the_led_cmd_.commands[0]);
}
SPECIFICPIN(x) is macro defined as:
#define SPECIFICPIN(X) (LED##X##_PIN)
What I was hoping for is a way to is a way to do something like this:
#define ioport_pin_t* ARR_LED[LED_COUNT] \
for (int j = 0; j < LED_COUNT; j++) ARR_LED[j] = SPECIFICPIN(j);
and then only need to call the following when I want to use the specific pin
LED_On(ARR_LED[some_number])
when I try to do that I get an ARR_LED undeclared (first use in this function) error.
When I try to call SPECIFICPIN(x) where x is an int iterator in a for loop for example, I get an error saying something like 'LEDx_PIN' undeclared...
You need to work on your terminology. An array of macros is not possible. Macros are no data type, but rather pure text replacement before your program is actually compiled.
I guess " populate an array using macros " is what you want to do. But it is not possible to do that in a compile-time loop - What you seem to want to achieve with your ioport_pin_t macro attempt. Macros do not have the capability to expand to more instances of text elements than you have initially given. There is no such feature as looping at compile time through macro expansions and do repetitive expansion of macros.
Your for loop loops at run-time, while the macro is being expanded at compile-time. Once you have made yourself aware what is done by the preprocessor what is done by the compiler, and what is done at run-time by the finished program, you will see that will not work.
Something like
#define P(X) {(LED##X##_PIN)}
ioport_pin_t *commands[LED_COUNT] = {
P(0), P(1), P(2),......}
#undefine P
Would be the closest thing possible to what you seem to want. Note the main use of the pre-processor is not to save you typing effort - You would be better off using copy & paste in your editor, achieve the same thing and have clearer code.
An array as tofro's answer is the way to go. However in cases that couldn't be solved simply with an array then there's another way with switch
#define SPECIFICPIN(X) (LED##X##_PIN)
void setpin(int pin, int value)
{
switch (pin)
{
case 1:
SPECIFICPIN(1) = value;
doSomething(); // if needed
break;
case x: ...
default: ...
}
}

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
{...}
;

Personal Preprocessor Directives

Being a C novice I would like to hear what Macro "define"s developers are using. I've been thinking about putting these in a header to skip verbosity I've become used to:
#define TS_ typedef struct {
#define _TS(x) } x;
#define I(x)_ { int i; for ( i = 1; i <= x; i++ ) {
#define _I } }
Can I add \n \t etc within these macros? As I would like to pass on my sourcecode minus the extra include:
#define TS_ typedef struct {\n
#define _TS(x) } x;\n
#define I(x)_ { int i;\n\tfor ( i = 1; i <= x; i++ ) {\n
#define _I \t}\n}\n
Would these work?
ie: Can I use the proprocessor to replace my sourcecode with my personal include to formatted source without the include ?
Links to good preprocessor tips and tricks also appreciated.
Before you get started, do not use macro names that begin with an underscore - these are reserved for compiler and standard library writers, and must not be used in your own code.
Additionally, I would say that the macros you suggest are all very bad ideas, because they hide from the reader what is going on. The only justification for them seems to be to save you a very small amount of typing. Generally, you should only be using macros when there is no sensible alternative. In this case there is one - simply write the code.
You can put whitespace in by escaping the newline
#define SOMETHING whatever\
This is part of the macro
But as others have said it's not really a great way to to do this.
It would be much better to look into editor macros so you could type the shortcut and have the editor expand it.
You are headed into a wrong path. DO NOT make up your own cpp directives that are unfamiliar to others - this will make your code hard to understand, and at some point maintain.
Try to find some good C code to read - good C code does not use these things, for a good reason.
DON'T DO IT. Nobody else will be able to read your code.
As a cautionary example, check out Steve Bourne's original sources for the Bourne shell, where he used macros to write the code in a kind of pidgin Algol style.
You could do this, but this sort of "personal language" is not generally used in the C world, especially if you expect anybody else to read your code in the future.
If you're doing this just for yourself, then feel free to #define whatever you want, but expect that once you start working with (or for) anybody else, you won't be able to continue using this sort of thing.
Using C macros unnecessarily can lead you into a world of pain, especially if you attempt to use it to expand code. There are uses for C macros, but this is not it.
Edit: I realize that my answer is tangential to your question, but I thought I should mention this since you say you are a C novice. Search for "C macro pitfalls" to get a full list of reasons why not to use macros. It's been previously discussed here.
In general, I strongly agree with the other respondents who tell you not to define your own macros purely for the sake of saving typing. The obfuscation is not worth it. Also, the particular macros you suggest are heinous. However, in Stroustrup's 1st Ed, he does something I rather like (sometimes):
#define Kase break; case
I became accustomed to the Python elif construct, so I often define the following:
#define elif(test) else if(test)
My purpose in doing this isn't to reduce typing, it's to keep indentation logical while maintaining consistent code width (I don't let my code go wider than 80 characters). I say this because to me this...
if(...) ...
else if(...) ...
else ...
...should be...
if(...)
{
...
}
else
if(...)
{
...
}
else
{
...
}
With my macro this becomes:
if(...)
{
...
}
elif(...)
{
...
}
else
{
...
}
It is always better to pass the loop variable to the macro.
A block - a macro has certain optimization problems. All compilers do not guarantee an optimized obj code for the "block scope" variables.
for example, the following code, when compiled with out any optimization options to gcc, prints two separate addresses for &i. And the same code when compiled with -O2 option will print the same address in both the blocks.
{
int i;
printf("address of i in first block is %u\n", &i);
}
{
int i;
printf("address of i in sec block is %u\n", &i);
}
Naming the language constructs appropriately makes the code more readable.
I like your idea, if you put it in the following way.
#define GREEN 1
#define YELLOW 2
#define RED 3
# define NUM_COLORS 3
#define COLOR_ITER (color,i) \
for(i=GREEN, color = colors[i]; \
i < NUM_COLORS; \
color = colors[++i])
int colors[3] = {GREEN, YELLOW, RED};
int
fun () {
int j;
color_t clr;
COLOR_ITER(clr, j) {
paint(clr);
}
}
Here, regardless of how it is written, the macro, COLOR_ITER, by its name, implies that you are looping for all available colors and doing "something" for each color. And this is a very easy-to-use macro.
And your quesion
Can I use the proprocessor to replace my sourcecode with my personal include to formatted source without the include ?
As everybody explained preprocessor will not help you in this case.
You can use your editor commands to automatically format your code, as you type it.

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