Convert int into string with C macro

Hau Yang
Hau Yang
Sep 9, 2018 · 2 min read

I was developing iota c language client APIs in the past few days. When I was writing unit test of the APIs I found the need of converting integer into string. It is piece of cake if I just simply call

sprintf ( char * str, const char * format, ... );

However, I found a interesting way to achieve this with macro when I was coding this time.

The same function can be achieved by defining macro with C’s preprocessor operator #

So with the following code we can easily convert a numer which is hard coded.

#define STR(x) #x

You can simply verify it with the following code.

#include <stdio.h>
#define STR(x) #x
int main()
{
printf("the output = %s", STR(123));
return 0;
}

the output is

the output is 123

However something is going wrong if we defined another macro TEST_INT

for integer 123

#include <stdio.h>
#define STR(x) #x
#define TEST_INT 123
int main()
{
printf("the output = %s", STR(TEST_INT));
return 0;
}

the output is

the output is TEST_INT

OMG why doesn’t it work?

The reason is the preprocessor take the macro name TEST_INT as parameter of the macro STR before expanding the macro TEST_INT instead of expanding the macro TEST_INT before taking it as parameter.

Then how could we solve this problem?

The answer is adding an extra level of macro.

See this demonstration.

#include <stdio.h>
#define STR_INDIR(x) #x
#define STR(x) STR_INDIR(x)
#define TEST_INT 123
int main()
{
printf("the output = %s", STR(TEST_INT));
return 0;
}

then things will be fine. Let’s see the output

the output is 123

The indirection way expanded the first level of macro at the first time. At this moment, the TEST_INT has been expanded into integer 123, and then, the 123 was taken as parameter of the second level of macro STR_INDIR(x)

However, if you declare a const int test_int = 123; then macro will be useless.

#include <stdio.h>
#define STR(x) #x
int main()
{
const int test_int = 123;
printf("the output = %s", STR(test_int));
return 0;
}

The reason is pretty simple.

macros are expanded during the preprocess time, so the macro would take the variable name as parameter on the above code.

the output is

the output is test_int

Hope this article could help confusing people hust like me.

Hau Yang

Written by

大學讀的是機械和電機。最近喜歡的東西是可以抱著睡的大娃娃。github: https://github.com/HowJMay

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade