Reputation: 1579
I want to add two macro definition and want to convert result into string in pre-processing stage itself i tried it in following ways but it doesn't work
#include <stdio.h>
#define TO_STRING_IND(arg) #arg
#define TO_STRING(arg) TO_STRING_IND(arg)
#define ABC 1
#define XYZ 2
#define TOTAL (ABC+XYZ)
#define total_str TO_STRING(TOTAL)
int main()
{
printf("total %d \n",TOTAL);
printf("total_str %s \n",total_str);
return 0;
}
output of this program is as follows,
total 3
total_str (1+2)
I expect total_str to be 3 in string.
Any suggestions ?
Upvotes: 1
Views: 202
Reputation: 40155
You can in addition preprocessor in the range of up to 256(BOOST_PP_LIMIT_MAG) if You can use the boost.
#include <stdio.h>
#include <boost/preprocessor/arithmetic/add.hpp>
#define TO_STRING_IND(arg) #arg
#define TO_STRING(arg) TO_STRING_IND(arg)
#define ABC 1
#define XYZ 2
#define TOTAL (ABC+XYZ)
#define total_str TO_STRING(BOOST_PP_ADD(ABC, XYZ))
int main()
{
printf("total %d \n",TOTAL);
printf("total_str %s \n",total_str);
return 0;
}
Upvotes: 2
Reputation: 3870
(ABC+XYZ) this will be replaced by (1+2). Then the TOTAL in your Program will be replaced by (1+2).
so printf("total %d \n",(1+2)); this will add the number and gives the output as 3.
But total_str will be replaced by "(1+2)", where (1+2) is a string.
The reason is TO_STRING((1+2)) will be replaced by #(1+2). # is Stringizing operator. it will convert the argument to string.
printf("total_str %s \n","(1+2)"); it can't add (1+2) because it is a string.
so you will get the result as (1+2).
Upvotes: 1
Reputation: 1352
The only place where the preprocessor does any calculation is in #if statements. Otherwise the preprocessor makes only textual replacements. Therefore it cannot be done in the preprocessor stage what you are trying to do.
Upvotes: 1