Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer to string converter(using macros)

Tags:

c

macros

I was doing basics of macros. I define a macro as follows:

#define INTTOSTR(int) #int

to convert integer to string.

Does this macro perfectly converts the integer to string? I mean are there some situations where this macro can fail?

Can I use this macro to replace standard library functions like itoa()?

for example:

int main()
{
    int a=56;
    char ch[]=INTTOSTR(56);
    char ch1[10];
    itoa(56,ch1,10);
    printf("%s %s",ch,ch1);
    return 0;
}

The above program works as expected.

Interestingly this macro can even convert float value to string.

for example:

INTTOSTR(53.5);

works nicely.

Till now I was using itoa function for converting int to string in all my projects. Can I replace itoa confidently in all projects. Because I know there is less overhead in using macro than function call.

like image 302
A.s. Bhullar Avatar asked Jul 11 '14 19:07

A.s. Bhullar


2 Answers

Macros execute during (before to be exact) compile time, so you can convert a literal number in your sourcecode to a string but not a number stored in a variable

In your example, INTTOSTR(56) uses the stringification operator of the preprocessor which eventually results in "56". If you called it on a variable, you'd get the variable name but not its content.

like image 161
ThiefMaster Avatar answered Oct 01 '22 06:10

ThiefMaster


In C, you can use itoa or if you are desperate and would like to avoid it, use snprintf for instance:

snprintf(my_str, sizeof(int), "%i", my_int);

The problem with your macro is that you are thinking about constants, but of course, your macro will be broken when you need to use a variable holding an integer. Your macro would try to stringify the macro name as opposed to the value it would be holding.

If you are fine with constants, your macro is "good", otherwise it is b0rked.

like image 31
lpapp Avatar answered Oct 01 '22 05:10

lpapp