3

I have a list of character definitions, like this:

#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6

(These are the two bytes that form the UTF-8 character "ö")

Is it possible to create a macro that takes the prefix (in this example "MYCHAR") and yields the string "\xC3\xB6"? (i.e. "ö")

In other words can the C-preprocessor create a static string (or array) out of static array-elements?

The end result should be usable by a function that has a string as parameter, for example:

printf(MY_MAGIC_MACRO(MYCHAR));

should print "ö".

3
  • 2
    You could of course do char ouml[] = { MYCHAR_1, MYCHAR_2, 0 }; Commented Oct 2, 2014 at 14:01
  • OK, but how can I use that in a function? - I added a clarification to the question. (BTW, you would need unsigned for UTF-8 characters) Commented Oct 2, 2014 at 14:19
  • You don't have to use unsigned char for UTF-8 characters; either signed char or plain char is also correct, usable, etc. However, in all respects except standard library support, unsigned char will be easier than a possibly (or definitely) signed char representation. Commented Oct 2, 2014 at 14:41

2 Answers 2

2

With numeric definitions as shown, it is moderately hard. However, assuming you have a C99 or later compiler, you can use a compound literal:

#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6

printf("%s", (char []){ MYCHAR_1, MYCHAR_2, '\0' });

If you're stuck with C89, then you probably don't have any good options other than to define an array variable and pass that to the function.

If you want a MY_MAGIC_MACRO(MYCHAR) to work, then you have to know how many names there are (2 per prefix in this example):

#define MY_MAGIC_MACRO(x) ((char []){ x##_1, x##_2, '\0' })

printf("%s\n", MY_MAGIC_MACRO(MYCHAR));

#include <stdio.h>

#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6

#define MY_MAGIC_MACRO(x) ((char []){ x##_1, x##_2, '\0' })

int main(void)
{
    printf("%s\n", (char[]){ MYCHAR_1, MYCHAR_2, '\0' });
    printf("%s\n", MY_MAGIC_MACRO(MYCHAR));
    return 0;
}

The output on a UTF-8 terminal is ö twice on separate lines.

Sign up to request clarification or add additional context in comments.

Comments

1

The closest thing to what you want to achieve that I can come up with:

#define MYCHAR_1 "\xC3"
#define MYCHAR_2 "\xB6"

const char STR [] = "ABC" MYCHAR_1 "DEF" MYCHAR_2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.