1

Considering the following string:

Page 1 of 100

Where 1 and 100 are not fixed values.

How could I define a C macro in order to render that string by passing the two values as arguments?

To be clear, the format has to be as follows:

#define PAGE_IDX_MACRO(x,y)
vdenotaris
  • 13,297
  • 26
  • 81
  • 132

2 Answers2

8

The # operator converts a preprocessor token to a string literal.

String literals are concatenated in C by simply adding a space between them, i.e "hello" "world" is equivalent to "helloworld".

So the macro should be:

#define PAGE_IDX_MACRO(x, n) ("Page " #x " of " #n)

Assuming it is called like this:

PAGE_IDX_MACRO(1, 100);

Where 1 and 100 are compile-time constants.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

You can concatenate strings via the double hash tag:

## provides a way to [concatenate actual arguments][1] during macro expansion.

[1]: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc09numnum.htm

from this question:

What do two adjacent pound signs mean in a C macro?

Community
  • 1
  • 1
Pierre Begon
  • 166
  • 13
  • Although I'm not sure this is realy needed here -- `#define PAGE_IDX_MACRO(x,y) Page x of y` should do, possibly stringized, probably by using another preprocessor indirection. I think nothing is really concatenated here. – Peter - Reinstate Monica Sep 29 '15 at 08:28