This is a bit of a pain because you need to provide storage for the string. In truth, macros can now be reserved only for conditional compilation.
Constants are best done with enumerated types, and macro functions are usually better than built-in functions (provided that inline is a proposal to the compiler, not a requirement).
If you insist on using a macro, the repository can be executed with static repository, although it has problems with threads, if you use them, and delay / reuse of the returned string.
You can also dynamically allocate a line, but then you need to free it when you are done, and handle the lack of memory.
Perhaps the easiest way is to require the macro user to provide their own repository according to:
#include <stdio.h> #define TEST2_STR(b,p) (sprintf(b,"PORT-%d",p),b) int main (void) { char buff[20]; puts (TEST2_STR(buff, 42)); return 0; }
which outputs:
PORT-42
In case the macro seems a bit confusing, it uses a comma operator in which the expression (a, b) evaluates both a and b and has the result b .
In this case, it computes sprintf (which fills the buffer), then "returns" the buffer. And even if you think you have never seen this before, you are probably mistaken:
for (i = 0, j = 9; i < 10; i++, j--) xyzzy[i] = plugh[j];
Despite the fact that most people think that the for function is a very different construct that can be used in many different places:
int i, j, k; i = 7, j = 4, k = 42; while (puts("Hello, world"),sleep(1),1);
(etc.).