如何在C中打印传递给函数的变量的名称?

时间:2018-06-26 04:18:11

标签: c

考虑以下代码:

#include <stdio.h>
#include <strings.h>
#define getName(var)  #var

struct books
{
  char title[100];
  char author[100];
  char subject[100];
  int bookid;
};

void printbooks(struct books book)
{
   printf("The title of %s %s\n",getName(book),book.title);
   printf("%s\n",book.author);
   printf("%s\n",book.subject);
   printf("%d\n",book.bookid);
}

struct books book1;

int main()
{

   strcpy(book1.title,"A tale of two cities");
   strcpy(book1.author,"Charles Dickens");
   strcpy(book1.subject,"Romance");
   book1.bookid = 1000;

   printbooks(book1);
}

我引入#define getName(var) #var宏的原因是按照以下方式打印输出:

The title of book1 is A tale of two cities

显然这是行不通的。有办法吗?

PS:我完全是偶然地碰到了这一点,实际上,似乎并没有真正的需要。但是我仍然想知道是否有可能。

3 个答案:

答案 0 :(得分:0)

使用宏的另一种方法:

#define PRINT_BOOK(_book_variable) \
    printf("The title of " #_book_variable " is %s\n%s\n%s\n%d\n", \
        _book_variable.title, \
        _book_variable.author, \
        _book_variable.subject, \
        _book_variable.bookid)

int main(void)
{
    struct books book1 = {.title="A tale of two cities", 
                          .author="Charles Dickens", 
                          .subject="Romance", 
                          .bookid=1000};
    PRINT_BOOK(book1);
}

请注意,用法将不同于您的原始方法。 宏不是函数。

答案 1 :(得分:0)

不好意思,我假设您确实不希望变量名使用某个代码段来标识一本带有书中数据的内存。

我建议通过以下代码实现所需的输出(我认为这是存储在任何给定书中的元信息的有意义属性,而不是任何处理它的C构造):

printf("The title of the book with ID %d is: %s\n", book1.bookid, book1.title);

或者,您可能正在处理一组特殊的书,每本书都有一定的语义。例如。比较两本书的发行日期(为演示目的,引入结构的另一个成员,一个整数纪元):

if(book1.date>book2.date) 
{
    printf("The first selected book is younger than the second selected book.\n");
} else if(book1.date<book2.date) 
{
    printf("The first selected book is older than the second selected book.\n");
} else
{
    printf("The two books were published at the same time.\n");
} 

答案 2 :(得分:0)

能否请您分享使用该代码获得的输出?

我尝试了代码,这是我得到的: The title of book A tale of two cities

这正是我所期望的。由于您是从printbooks()函数调用宏,因此它将打印本地变量名称book

如果要打印book1,则需要从main()调用宏。这是我从main()调用宏时的输出。

The title of book1 A tale of two cities

p.s。代码中缺少“是”。