Why brack an rval - c

Please see the following snippet of C code:
PM_RAISE(retexn, exn)
do
{
retexn = (exn);
gVmGlobal.errFileId = __FILE_ID__;
gVmGlobal.errLineNum = (uint16_t)__LINE__;
} while (0)
On the 4th line, why is exn surrounded by brackets?
EDIT (In reply to IntermediateHacker) Here is the original snippet of code:
#if __DEBUG__
#define PM_RAISE(retexn, exn) \
do \
{ \
retexn = (exn); \
gVmGlobal.errFileId = __FILE_ID__; \
gVmGlobal.errLineNum = (uint16_t)__LINE__; \
} while (0)
#else
#define PM_RAISE(retexn, exn) \
retexn = (exn)
#endif

It's just considered good practice to wrap macro arguments in brackets. It doesn't help much in your example, but say you had:
#define multiply(a, b) a * b
and used it with:
multiply(4 + 3, 2)
it would expand to
4 + 3 * 2
which is obviously not the expected result (3 would be multiplied by 2 first).

Well, this is guess work on my part, but I think it's to enable entering an arithmetic expression as exn.
Here's what I mean:
/ * If I use: */
PM_RAISE( whatever, 18 / 9 + 5 );
/* It will generate */
whatever = (18 / 9 + 5);
/* which is good. */
Also, it's good practice to include brackets in macro functions like #James has pointed out.

Related

How to shorten these lines using preprocessor?

I have these lines in my code and was thinking that there may be some nice way to use preprocessor to generate these lines (0 through 31).
Mem_type MEM_0[MAX_NUM_MEM];
Mem_type MEM_1[MAX_NUM_MEM];
Mem_type MEM_2[MAX_NUM_MEM];
Mem_type MEM_3[MAX_NUM_MEM];
Mem_type MEM_4[MAX_NUM_MEM];
Mem_type MEM_5[MAX_NUM_MEM];
...
Mem_type MEM_30[MAX_NUM_MEM];
Mem_type MEM_31[MAX_NUM_MEM];
Mem_type *MEM[NUM_BANKS];
MEM[0] = MEM_0;
MEM[1] = MEM_1;
MEM[2] = MEM_2;
MEM[3] = MEM_3;
MEM[4] = MEM_4;
MEM[5] = MEM_5;
...
MEM[30] = MEM_30;
MEM[31] = MEM_31;
For example, something like:
#define Gen(n) MEM[n] = MEM_n
#for (k=0; k<32; k++) Gen(k);
(The reason why I don't do like the below is that I found that my machine has some maximum contiguous array size limit, so I tried to split it into separate arrays so that I can have larger aggregated MEM size.)
Mem_type MEM[NUM_BANKS][MAX_NUM_MEM];
Using boost/preprocessor/repetition/repeat.hpp :
#include <boost/preprocessor/repetition/repeat.hpp>
class Mem_type {};
#define MAX_NUM_MEM 5
#define NUM_BANKS 5
#define MEM_DECL(z, n, text) Mem_type MEM_## n[MAX_NUM_MEM];
#define MEM_MEMB(z, n, text) MEM_## n,
// expands to `Mem_type MEM_?[MAX_NUM_MEM];`
BOOST_PP_REPEAT(NUM_BANKS, MEM_DECL, ())
Mem_type *MEM[NUM_BANKS] = {
// expands to `MEM_?,`
BOOST_PP_REPEAT(NUM_BANKS, MEM_MEMB, ())
};
There are articles on the net about symbolic computations on preprocessing stage, one typical instance would be http://jhnet.co.uk/articles/cpp_magic
If the machinery defined there is too much for you and you don't care much about the prettiness of generated code you could use a cheap alternative, something like (untested):
#define ONE_MEM(i, a) MemType mem_ ## a[MAX_MEM]; mem[i] = mem_ ## a
#define MEM_1(i, a) ONE_MEM(i, a); ONE_MEM(i + 1, a ## 1)
#define MEM_2(i, a) MEM_1(i, a); MEM_1(i + 2, a##2)
#define MEM_4(i, a) MEM_2(i, a); MEM_2(i + 4, a##4)
and so forth, now it's logarithmic in amount of macros defined.
(Haven't tested it, the actual definition might need a concat indirection or two.)
There can be improvements, like declaring a macro parameter to substitute for mem etc.
The stack is very limited and should not be used to allocate huge data structures like this as discussed here. Instead try to allocate your memory using new[]. If you do need multidimensional arrays you can use an array of pointers that point to arrays pointing to your structures as described here.
However as your initial intention was to have a single array, this should do the trick without the need of the preprocessor:
Mem_type* MEM = new Mem_type[MAX_NUM_MEM]; // MAX_NUM_MEM is multiplied by NUM_BANKS here
// do things [...]
delete[] MEM;
MEM = nullptr;
It would be an idea to wrap this up in a class, allocate in the constructor, throw an exception if allocation fails and deallocate in the destructor.
Using dynamic allocation with STL vectors:
#include <vector>
class Mem_type {};
const int MAX_NUM_MEM = 5;
const int NUM_BANKS = 5;
// allocates NUM_BANKS vectors with MAX_NUM_MEM objects of Mem_type
std::vector<std::vector<Mem_type>> MEM(NUM_BANKS, std::vector<Mem_type>(MAX_NUM_MEM));
You can use an X Macro along with token concatenating
#define LIST_OF_MEMS \
X(0) \
X(1) \
X(2) \
X(3) \
X(4) \
X(5) \
... \
X(30) \
X(31) \
Now you can use it every time you want to do anything with all the MEMs. Note that using all caps for a variable name is a bad idea
// declaration
#define X(num) Mem_type mem_##num[MAX_NUM_MEM];
LIST_OF_MEMS
#undef X
// assignment
#define X(num) MEM[num] = mem_##num;
LIST_OF_MEMS
#undef X

Macro for run-once conditioning

I am trying to build a macro that runs a code only once.
Very useful for example if you loop a code and want something inside to happen only once. The easy to use method:
static int checksum;
for( ; ; )
{
if(checksum == 0) { checksum == 1; // ... }
}
But it is a bit wasteful and confusing. So I have this macros that use checking bits instead of checking true/false state of a variable:
#define CHECKSUM(d) static d checksum_boolean
#define CHECKSUM_IF(x) if( ~(checksum_boolean >> x) & 1) \
{ \
checksum_boolean |= 1 << x;
#define CHECKSUM_END }1
The 1 at the end is to force the user to put semi-colon at the end. In my compiler this is allowed.
The problem is figuring out how to do this without having the user to specify x (n bit to be checked).
So he can use this:
CHECKSUM(char); // 7 run-once codes can be used
for( ; ; )
{
CHECKSUM_IF
// code..
CHECKSUM_END;
}
Ideas how can I achieve this?
I guess you're saying you want the macro to somehow automatically track which bit of your bitmask contains the flag for the current test. You could do it like this:
#define CHECKSUM(d) static d checksum_boolean; \
d checksum_mask
#define CHECKSUM_START do { checksum_mask = 1; } while (0)
#define CHECKSUM_IF do { \
if (!(checksum_boolean & checksum_mask)) { \
checksum_boolean |= checksum_mask;
#define CHECKSUM_END \
} \
checksum_mask <<= 1; \
} while (0)
#define CHECKSUM_RESET(i) do { checksum_boolean &= ~((uintmax_t) 1 << (i)); } while (0)
Which you might use like this:
CHECKSUM(char); // 7 run-once codes can be used
for( ; ; )
{
CHECKSUM_START;
CHECKSUM_IF
// code..
CHECKSUM_END;
CHECKSUM_IF
// other code..
CHECKSUM_END;
}
Note, however, that that has severe limitations:
The CHECKSUM_START macro and all the corresponding CHECKSUM_IF macros must all appear in the same scope
Control must always pass through CHECKSUM_START before any of the CHECKSUM_IF blocks
Control must always reach the CHECKSUM_IF blocks in the same order. It may only skip a CHECKSUM_IF block if it also skips all subsequent ones that use the same checksum bitmask.
Those constraints arise because the preprocessor cannot count.
To put it another way, barring macro redefinitions, a macro without any arguments always expands to exactly the same text. Therefore, if you don't use a macro argument to indicate which flag bit applies in each case then that needs to be tracked at run time.

How #define work? Strange result for CUBE(y) y*(y*y)

#include<stdio.h>
#include<conio.h>
#define CUBE(y)y*(y*y)
main()
{
int j;
j = CUBE(-2+4);
printf("value of j = %d",j);
getch();
}
Output of this code is -26. I just want to know how this code give -26 as an output. How #define work in this code. I know that #define permanent fix value for a variable or method but don't how this work for CUBE here. Can somebody please describe this step by step, means in easy way.
It does:
j = -2 + 4 * (-2 + 4 * -2 + 4)
A more correct definition of CUBE would be
#define CUBE(y) ((y)*(y)*(y))
You should figure it out by yourself by using -E flag :
gcc test.c -E
# 1 "test.c"
# 1 "<command-line>"
# 1 "test.c"
main()
{
int j;
j = -2+4*(-2+4*-2+4); // <-- Check this substitution
printf("value of j = %d",j);
getch();
}
To cube numbers you should be using () to change precedence and order of evaluation :-
#define CUBE(y) (( y )*( y )*( y ))
which will give after using -E flag :
j = (( -2+4 )*( -2+4 )*( -2+4 ));
I know that #define permanent fix value for a variable or method
You can't know that because it's wrong. The preprocessor works by token replacement. Whenever it sees the token sequence CUBE(some tokens) it replaces it with
some tokens * ( some tokens * some tokens )
Now do the replacement of some tokens with -2+4 yourself and do the math.
The preprocessor doesn't even know what a variable or object or method is. It operates purely in terms of preprocessing tokens (little chunks of characters; see the ISO C Standard for details).
It expands as is :
-2+4*(-2+4*-2+4) = -2 +4(-6)= -26
To fix it surround y with ()
#define CUBE(y) ((y)*(y)*(y))
so you will get :
((-2+4) * (-2+4) * (-2+4))

Looking for a good explanation of the table generation macro idiom

I want to make this clear up front : I know how this trick works, what I want is a link to a clear explanation to share with others.
One of the answers to a C macro question talks about the "X macro" or "not yet defined macro" idiom. This involves defining something like:
#define MAGIC_LIST \
X(name_1, default_1) \
X(name_2, default_2) \
...
Then to create, say, an array of values with named indices you do:
typedef enum {
#define X(name, val) name,
MAGIC_LIST
#undef X
} NamedDefaults;
You can repeat the procedure with a different #define for X() to create an array of values, and maybe debugging strings, etc.
I'd like a link to a clear explanation of how this works, pitched at someone who is passably familiar with C. I have no idea what everyone usually calls this pattern, though, so my attempts to search the web for it have failed thus far.
(If there is such an explanation on SO, that'd be fine...)
The Wikipedia page about the C preprocessor mentions it but is not brilliantly clear IMO:
http://en.wikipedia.org/wiki/C_preprocessor#X-Macros
I wrote a paper about it for my group; feel free to use this if you wish.
/* X-macros are a way to use the C pre-processor to provide tuple-like
* functionality that would not otherwise be easy to implement in C.
* Any time you find yourself writing a comment that says something
* like "These values must be kept in sync with the values in typedef enum
* foo_t", or adding a new item to a list and copying and pasting functions
* to handle it, then X-macros are probably a better way to implement the
* behaviour you want.
*/
/* Begin with the main definition of the table of tuples. This can be directly
* in the header file, or in a separate #included template file. This example
* is from some hardware revision reporting code.
*/
/*
* Board versions
* Upper bound resistor value, hardware version, hardware version string
*/
#define APP_HW_VERSIONS \
X(0, HW_UNKNOWN, UNKNOWN_HW_VER) \
X(8, HW_NO_VERSION, "XDEV") /* Unversioned board (e.g. dev board) */ \
X(24, HW_REVA, "REVA") \
X(39, HW_REVB, "REVB") \
X(54, HW_REVD, "REVD") \
X(71, HW_REVE, "REVE") \
X(88, HW_REVF, "REVF") \
X(103,HW_REVG, "REVG") \
X(118,HW_REVH, "REVH") \
X(137,HW_REVI, "REVI") \
X(154,HW_REVJ, "REVJ") \
/* add new versions above here */ \
X(255,HW_REVX, "REVX") /* Unknown newer version */
/* Now, any time you need to use the contents of this table, you redefine the
* X(a,b,c) macro to give the behaviour you want. In the hardware revision
* example, the first thing we need is an enumerated type giving the
* possible options for the value of the hardware revision.
*/
#define X(a,b,c) b,
typedef enum {
APP_HW_VERSIONS
} app_hardware_version_t;
#undef X
/* The next thing we need in this example is some code to extract the
* hardware revision from the value of the version resistors.
*/
static app_hardware_version_t read_board_version(
board_aio_id_t identifier,
board_aio_val_t value
)
{
app_hardware_version_t app_hw_version;
/* Determine board version based on ADC reading */
#define X(a,b,c) if (value < a) {app_hw_version = b;} else
APP_HW_VERSIONS
#undef X
{
app_hw_version = HW_UNKNOWN;
}
return app_hw_version;
}
/* Now we have two different places that need to extract the hardware revision
* as a string: the MMI info screen and the ATI command.
*/
/* in the info screen code: */
switch(ver)
{
#define X(a,b,c) case b: ascii_to_display_string((lcd_char_t *) &app[0], c, HW_VER_STRING_LEN); break;
APP_HW_VERSIONS
#undef X
default:
ascii_to_display_string((lcd_char_t *) &app[0], UNKNOWN_HW_VER, HW_VER_STRING_LEN);
break;
}
/* in the ATI handling code: */
switch(ver)
{
#define X(a,b,c) case b: strncpy(&p_data, (const uint8_t *) c, HW_VER_STRING_LEN); break;
APP_HW_VERSIONS
#undef X
default:
strncpy_write(&p_data, (const uint8_t *) UNKNOWN_HW_VER, HW_VER_STRING_LEN);
break;
}
/* Another common example use case is auto-generation of accessor and mutator
* functions for a list of storage keys
*/
/* First the tuple table */
/* Configuration items:
* Storage key ID, name, type, min value, max value
*/
#define CONFIG_ITEMS \
X(1234, DEVICE_ID, uint16_t, 0, 0xFFFF) \
X(1235, NUM_CONNECTIONS, uint8_t, 0, 8) \
X(1236, ENABLE_LOGGING, bool_t, 0, 1) \
X(1237, SECURITY_KEY, uint32_t, 0, 0xFFFFFFFF)
/* add new items above here */
/* Generate the enumerated type of keys */
#define X(a,b,c,d,e) CONFIG_ITEM_##b = a,
typedef enum {
CONFIG_ITEMS
} config_item_t;
#undef X
/* Generate the accessor functions */
#define X(a,b,c,d,e) \
int get_config_item_##b(void *p_buf) \
{ \
return read_from_key(a, sizeof(c), p_buf); \
}
CONFIG_ITEMS
#undef X
/* Generate the mutator functions */
#define X(a,b,c,d,e) \
bool_t set_config_item_##b(void *p_buf) \
{ \
c val = * (c*) p_buf; \
if (val < d || val > e) return FALSE; \
return write_to_key(a, sizeof(c), p_buf); \
}
CONFIG_ITEMS
#undef X
/* Or, if you prefer, one big generic accessor function */
int get_config_item(config_item_t id, void *p_buf)
{
switch (id)
{
#define X(a,b,c,d,e) case a: return read_from_key(a, sizeof(c), p_buf); break;
CONFIG_ITEMS
#undef X
default:
return 0;
}
}
/* and one big generic mutator function */
bool_t set_config_item(config_item_t id, void *p_buf)
{
switch (id)
{
#define X(a,b,c,d,e) \
case a: \
{ \
c val = * (c*) p_buf; \
if (val < d || val > e) return FALSE; \
return write_to_key(a, sizeof(c), p_buf); \
}
CONFIG_ITEMS
#undef X
default:
return FALSE;
}
}
/* Finally let's add a logging function to dump all the config items */
void log_config_items(void)
{
#define X(a,b,c,d,e) \
{ \
c val; \
if (read_from_key(a, sizeof(c), &val) == sizeof(c)) \
{ printf("CONFIG_ITEM_##b (##a): 0x%x\n", val); } \
else { printf("CONFIG_ITEM_##b (##a): Failed to read\n"); } \
}
CONFIG_ITEMS
#undef X
}
/* Now, when you need to add a new item to your list of config keys, you don't
* need to update the enumerated type and copy and paste new get and set
* functions for each new key; you simply update the table of tuples and the
* pre-processor takes care of the rest.
*/

Writing a C Macro

I have to write a macro that get as parameter some variable, and for each two sequential bits with "1" value replace it with 0 bit.
For example: 10110100 will become 10000100.
And, 11110000->00000000
11100000->100000000
I'm having a troubles writing that macro. I've tried to write a macro that get wach bit and replace it if the next bit is the same (and they both 1), but it works only for 8 bits and it's very not friendly...
P.S. I need a macro because I'm learning C and this is an exercise i found and i couldn't solve it myself. i know i can use function to make it easily... but i want to know how to do it with macros.
Thanks!
#define foo(x,i) (((x) & (3<<i)) == (3<<i)) ? ((x) - (3 << i)) : (x)
#define clear_11(x) foo(foo(foo(foo(foo(foo(foo(foo(foo(x,8),7),6),5),4),3),2),1),0)
This will do the job. However the expansion is quite big and compilation may take a while. So do not try this at work ;)
#define clear_bit_pairs(_x) ((_x)&~(((_x)&((_x)>>1))*3))
#define clear_bit_pairs(_x) ((_x) ^ ((((_x)&((_x)>>1))<<1) | ((_x)&((_x)>>1))) )
This will work, but it does not pair up. If it finds the consecutive '1' it will just erase. for example 11100000 will become 00000000 because the first 111 are consecutive.
#define foo(x) ({ \
typeof(x) _y_ = x; \
for(int _i_ = 0; _i_ < (sizeof(typeof(x)) << 3) + 1; _i_++) { \
if((_y_ >> _i_ & 3) == 3) { \
_y_ &= ~(3 << _i_); \
} \
} \
_y_; \
})
This probably only works in GCC, since it uses inline statements. I haven't tested it, so it probably doesn't work at all. It is your job to make it work. :-)
The nice thing about this is that it will work with any integral type. It also doesn't rely on any external functions. The downside is that it is not portable. (And I realize that this is sort of cheating.)

Resources