Reputation: 41
Im creating a macro that accept 2 strings: variable string and literal string. How do I combine both of them to a function which accept single variable?
I know that we can combine 2 literal string in a macro.
#define LOGPRINT(x,y) func(x y)
#define LOGPRINTSINGLE(x) func(x)
func(char *fmt)
{
printf(fmt);
}
Below code works fine:
char * test = "hey ";
LOGPRINT("hello ", "world!");
LOGPRINTSINGLE(hey);
But below code fails.
LOGPRINT(test, "world!");
How do I combine variable string test to literal string "world" in the macro? Expected result is "hey world" is passed to the func().
**Edit/Note: Rule is I only allowed to change code on this side and not the caller and func().
Upvotes: 3
Views: 1894
Reputation: 231
Maybe not the most beautiful or safe macro in the world, but it works :-)
#include <stdio.h>
#include <string.h>
#define LOGPRINT(x,y) \
{ \
char dest[strlen(x) + strlen(y) + 1]; \
memcpy(dest, x, strlen(x)); \
memcpy(dest + strlen(x), y, strlen(y)); \
dest[strlen(x) + strlen(y)] = 0; \
func(dest); \
}
#define LOGPRINTSINGLE(x) func(x)
void func(char *fmt)
{
printf(fmt);
}
int main()
{
char * test = "hey ";
LOGPRINT("hello ", "world!");
printf("\n");
LOGPRINTSINGLE(test);
printf("\n");
LOGPRINT(test, "world!");
return 0;
}
Output:
hello world!
hey
hey world!
Upvotes: 2
Reputation: 363
Pretty simple using c++ string if you include "string" STL
change #define LOGPRINT(x,y) func(x y)
to #define LOGPRINT(x,y) func((std::string(x) + std::string(y)).data())
or #define LOGPRINT(x,y) func(std::string(x).append(y).data())
Upvotes: 1