vdenotaris
vdenotaris

Reputation: 13637

String as macro with arguments in C

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)

Upvotes: 1

Views: 117

Answers (2)

Lundin
Lundin

Reputation: 213810

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.

Upvotes: 8

Pierre Begon
Pierre Begon

Reputation: 166

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?

Upvotes: 0

Related Questions