Hi all.. i was looking for macro which can expand like the following:
FILL_BUFF(4) should be expanded as (0xFF, 0xFF, 0xFF, 0xFF)... what can be the macro written for the above expansion..
Hi all.. i was looking for macro which can expand like the following:
FILL_BUFF(4) should be expanded as (0xFF, 0xFF, 0xFF, 0xFF)... what can be the macro written for the above expansion..
Macros don't have conditional controls such as loops - they are very simple.
It's common to see a group of macros in a header covering all the common expansions, e.g.
#define FILL_BUFF_1 (0xFF)
#define FILL_BUFF_2 (0xFF,0xFF)
#define FILL_BUFF_3 (0xFF,0xFF,0xFF)
#define FILL_BUFF_4 (0xFF,0xFF,0xFF,0xFF)
Hmm, maybe via memset:
#define FILL_BUFF(buf, n) memset(buff, 0xff, n)
But I am not sure that is such a good idea
PP got it - almost. Abusing the C preprocessor again. On the other hand, it deserves nothing better.
#define FILL_BUFF(N) FILL_BUFF_ ## N
#define FILL_BUFF_1 (0xFF)
#define FILL_BUFF_2 (0xFF,0xFF)
#define FILL_BUFF_3 (0xFF,0xFF,0xFF)
#define FILL_BUFF_4 (0xFF,0xFF,0xFF,0xFF)
You may want to look at the boost preprocessor library. Especially the BOOST_PP_REPEAT_z
macros:
#define DECL(z, n, text) text ## n = n;
BOOST_PP_REPEAT(5, DECL, int x)
results in:
int x0 = 0; int x1 = 1; int x2 = 2; int x3 = 3; int x4 = 4;
In your case you could do:
#define FILL_BUFF_VALUE(z, n, text) text,
#define FILL_BUFF(NPLUSONE, VALUE) { BOOST_PP_REPEAT(NPLUSONE, FILL_BUFF_VALUE, VALUE } VALUE )
int anbuffer[] = FILL_BUFF(4 /* +1 */,0xff); // anbuffer will have length 5 afterwards
which would expand to
int anbuffer[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
@sebastian: thanx for the link.. but it doesnt work in my C environment. i have tried the below, but somehow doesnt work:
#define X
#define FILL_BUFF (int *)(0xFF, 0xFF, .. 0xFF) // not sure whether syntactically correct
#define LOOKUP \
X(0x13, NULL), \
X(0x14, FILL_BUFF)
#undef X #define X(a,b) b
int *buff_ptr[2] = {LOOKUP};
will i be able to de-reference the elements of buff_ptr.. if so, how?