K
K
KiVa2019-04-23 19:13:25
C++ / C#
KiVa, 2019-04-23 19:13:25

How to form a string using C macros?

Good day!
In someone else's header file there is: You need to get:
#define number 10

#define stamp "stamp n.10"  // где 10 берётся выше, в строке пробел обязателен

Obviously, the head-on solution does not work:
#define mkstr(s) # s
#define concat(a,b) a ## b
#define stamp mkstr(concat(stamp n., number))

The problem is mkstr () which expands before concat (). I know that here it is necessary to use "magic" with an intermediate macro, but I can't figure out how to implement it.
Please help with the correct decision on the formation of the specified string using C macros.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogachev, 2019-04-23
@sfi0zy

I know that here it is necessary to use "magic" with an intermediate macro, but I can't figure out how to implement it.

If I'm not confusing anything, then something like this should turn out:
#define number 10

#define mkstr2(s) #s
#define mkstr(s) mkstr2(s)
#define stamp "stamp n." mkstr(number)

#include <stdio.h>

int main()
{
    printf("%s", stamp); // stamp n.10
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question