0

I have the following function foo() and the macro FOO(str).

void foo(const char *fmt, ...) {
   va_list args;
   va_start(args,fmt);
   vsprintf(msgbuff,fmt,args);
   va_end(args);
   printf("%s\n",msgbuff);
}

#define FOO(str)\
foo str;           // No need of brackets as they are coming in 'str'

I used to call the macro like below:

FOO(("My %s is %s\n","Name","Bala"));

Now my Requirement is:

Macro FOO(str) should not call my function foo() directly but instead it should call it through another function like func().

Finally my macro should be like below

#define FOO(str)\
func(#str) // Do I need to Stringizing str? 

My question is, how can I call function foo() from inside func()? Please suggest any possible implementation.

13
  • Sounds like you need a variadic macro. Commented Jun 22, 2017 at 11:54
  • 1
    Why do you want to use a macro at all? Never use a macro when a function will do the job as well! And the first version of the macro is missleading and obfuscates your code. Commented Jun 22, 2017 at 11:57
  • Please provide the definition of func(). Commented Jun 22, 2017 at 11:58
  • Hi olaf , iam changing only the internal implementation of macro in my existing project. so i cannot change the macro usage . i can only change its implentation Commented Jun 22, 2017 at 13:38
  • Hi kampling ,just for example i have said func(). actually i need to know how to call foo() inside func() Commented Jun 22, 2017 at 13:42

1 Answer 1

-1

You can use variadic macro

#define FOO(...) \
fun(__VA_ARGS__);

And call it like this

FOO("A", "B", "C")

EDIT:

As pointed out by Olaf, this is not encouraged and can be replaced by a direct function call

5
  • The question does not say anything about using a variable number of arguments. And even if, as given a macro is not necessary, hence strongly discouraged. Commented Jun 22, 2017 at 11:58
  • 1
    @lapinozz: He tagged his question with C and not C++. Commented Jun 22, 2017 at 12:05
  • Right, foolish me
    – lapinozz
    Commented Jun 22, 2017 at 12:06
  • I did no way point out macros are useless (or almost useless). And the main issue still applies: There are no variable arguments. Commented Jun 22, 2017 at 12:07
  • Hi the problem is i can use the macro only like this - FOO(("My %s is %s\n","Name","Bala")); .... I need to call foo() from a functio func(). Commented Jun 22, 2017 at 13:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.