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 "ö".
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With