thirdeye
thirdeye

Reputation: 302

How to stringize by concatenating two tokens using token-pasting in c using macros?

Want to concatenate two tokens and convert the result to string using macros and token-pasting and stringizing operators only.

#include <stdio.h>

#define concat_(s1, s2) s1##s2
#define concat(s1, s2) concat_(s1, s2)

#define firstname stack
#define lastname overflow

int main()
{
    printf("%s\n", concat(firstname, lastname));
    return 0;
}

but the above throws undeclared error as below

error: ‘stackoverflow’ undeclared (first use in this function)

tried having # to stringize s1##s2

#define concat_(s1, s2) #s1##s2 \\ error: pasting ""stack"" and "overflow" does not give a valid preprocessing token

Upvotes: 2

Views: 184

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126203

If you want to concatenate and then stringize, you need to concatenate first, and then stringize:

#include <stdio.h>

#define concat_(s1, s2) s1##s2
#define concat(s1, s2) concat_(s1, s2)
#define string_(s) #s
#define string(s) string_(s)

#define firstname stack
#define lastname overflow

int main()
{
    printf("%s\n", string(concat(firstname, lastname)));
    return 0;
}

The problem with just adding a # to the concat_ macro is that it will try to stringize before the concat.

Of course, with strings, there's no actual need to concatenate them with the preprocessor -- the compiler will automatically combine two strings literals with nothing between them except whitespace into one:

#include <stdio.h>

#define string_(s) #s
#define string(s) string_(s)

#define firstname stack
#define lastname overflow

int main()
{
    printf("%s\n", string(firstname) string(lastname));
    return 0;
}

This also avoids problems if the things you want to concatenate aren't single tokens and/or don't become a single token, both of which cause undefined behavior.

Upvotes: 4

Related Questions