inquisitive
inquisitive

Reputation: 1680

Regarding macros

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..

Upvotes: 1

Views: 291

Answers (4)

Sebastian
Sebastian

Reputation: 4950

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

Upvotes: 2

Gunther Piez
Gunther Piez

Reputation: 30419

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)

Upvotes: 2

laura
laura

Reputation: 7332

Hmm, maybe via memset:

#define FILL_BUFF(buf, n) memset(buff, 0xff, n)

But I am not sure that is such a good idea

Upvotes: 1

PP.
PP.

Reputation: 10864

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)

Upvotes: 2

Related Questions