字符串化函数 return 值?

Stringize function return value?

假设我有一个随机函数 func(),我如何将它的 return 值字符串化? 我试过这样做-

#define STR1(x) #x
#define STR2(x) STR1(x)

int func(void){
    return 1;
}

int main(void)
{
   puts((STR2(func()));
}

但这字面上打印了 func(),我在某处读到过双字符串化,如果我在宏上使用 STR2 这会起作用,因为它会首先扩展宏,并且然后将其字符串化,但为什么在字符串化之前不计算 func 的结果?

字符串化是宏替换中的预处理操作,它只对源代码标记进行操作。它不能用于 运行 时间值。

要将值转换为字符串,您可以使用 snprintf。但是,由于您是直接输出字符串,因此您可以简单地使用 printf("%d", func());.

假设您想要的字符串不仅仅是 puts,您可以通过包含 <stdio.h><stdlib.h> 并使用:

将值转换为字符串
    // 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);

预处理器将看到这一点(为方便起见添加的行):

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.  }

然后它将处理第一行的第一个预处理指令。这将导致以下预处理代码:

2.  #define STR2(x) #x

3.  int func(void){
4.      return 1;
5.  }

6.  int main(void)
7.  {
8.     puts((STR2(func()));
9.  }

第 2 行的预处理器指令现在可以处理了。这将导致以下预处理代码:

3.  int func(void){
4.      return 1;
5.  }

6.  int main(void)
7.  {
8.     puts(( "func()" );
9.  }

此代码现已完全预处理,可以传递给编译器。 (顺便说一句,由于括号不平衡,会导致编译器错误)