Reputation: 23
Suppose I have a random function func()
, how would i stringize its return value?
I tried doing this-
#define STR1(x) #x
#define STR2(x) STR1(x)
int func(void){
return 1;
}
int main(void)
{
puts((STR2(func()));
}
But this literally prints func(), I read about double stringization somewhere, and this would've worked if I had used STR2
on a macro, since it would've expanded the macro first, and then stringized that, but why does this not compute the result of func
before stringizing it?
Upvotes: 0
Views: 112
Reputation: 223747
Stringification is a preprocessing operation in macro replacement, and it only operates on source code tokens. It cannot be used on run-time values.
To convert a value to a string, you can use snprintf
. However, as you are directly outputting the string, you can simply use printf("%d", func());
.
Supposing you want the string for more than just puts
, you can convert the value to a string by including <stdio.h>
and <stdlib.h>
and using:
// Store the value so we do not call func multiple times.
int t = func();
// Ask snprintf how much space we need. Add one for the terminating null character.
size_t n = snprintf(NULL, 0, "%d", t) + 1;
// Ask for memory and check that we got it.
void *p = malloc(n);
if (!p)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// Convert the value to a string.
snprintf(p, n, "%d", t);
// Use the string as desired.
puts(p);
// Release the memory.
free(p);
Upvotes: 1
Reputation: 22255
The preprocessor will see this (lines added for convenience):
1. #define STR1(x) #x
2. #define STR2(x) STR1(x)
3. int func(void){
4. return 1;
5. }
6. int main(void)
7. {
8. puts((STR2(func()));
9. }
It will then process the first preprocessing directive on line one. This will result in the following pre-processedcode:
2. #define STR2(x) #x
3. int func(void){
4. return 1;
5. }
6. int main(void)
7. {
8. puts((STR2(func()));
9. }
The preprocessor directive of line 2 is now ready to be processed. This will result in the following preprocessed code:
3. int func(void){
4. return 1;
5. }
6. int main(void)
7. {
8. puts(( "func()" );
9. }
This code is now fully pre-processed, and ready to be passed to the compiler. (which, incidentally, will cause a compiler error because of the unbalanced parenthesis)
Upvotes: 0