Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro in C to call a function returning integer and then return a string

Tags:

c

function

macros

I have a function which returns an integer value. Now I want to write a macro which call this function, gets the return value and prepends a string to it and return the resultant string.

I have tried this:

#define TEST(x)        is_enabled(x)

I call this macro in the main function as:

int ret = 0;
ret = TEST(2);
printf("PORT-%d\n", ret);

This works perfectly. However I want the macro to return the string PORT-x, where, x is the return value of the called function. How can I do this?

EDIT :

I also tried writing it into multiple lines as:

#define TEST(x)\
{\
    is_enabled(x);\
}

And called it in the main function as:

printf("PORT-%d\n", TEST(2));

But this gives a compile time error:

error: expected expression before â{â token
like image 949
iqstatic Avatar asked Nov 25 '14 07:11

iqstatic


1 Answers

Use a function, not a macro. There is no good reason to use a macro here.

You can solve it by using sprintf(3), in conjonction with malloc or a buffer. See Creating C formatted strings (not printing them) or man pages for details.

About your edit: You don't need to use braces {} in a macro, and they are causing your error as preprocessing would translate it to something like

printf("format%d", {
  is_enabled(x);
}); 

To better understand macros, run gcc or clang with -E flag, or try to read this article: http://en.wikipedia.org/wiki/C_preprocessor

like image 94
Antzi Avatar answered Nov 14 '22 22:11

Antzi