Convert int into string with C macro
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) #xYou can simply verify it with the following code.
#include <stdio.h>
#define STR(x) #xint main()
{
printf("the output = %s", STR(123)); return 0;
}
the output is
the output is 123However something is going wrong if we defined another macro TEST_INT
for integer 123
#include <stdio.h>
#define STR(x) #x
#define TEST_INT 123int main()
{
printf("the output = %s", STR(TEST_INT)); return 0;
}
the output is
the output is TEST_INTOMG 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 123int main()
{
printf("the output = %s", STR(TEST_INT));return 0;
}
then things will be fine. Let’s see the output
the output is 123The 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) #xint 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_intHope this article could help confusing people hust like me.
