使用宏初始化结构

时间:2014-07-24 06:11:56

标签: c macros struct

我一直在搜索,找不到任何东西。考虑这个结构

typedef struct student
{
    char name[40];
    char grade;
}Student;

如何使用参数初始化结构的宏?

的内容
Student John = STUDENT(John, A); 

其中STUDENT是定义的宏

2 个答案:

答案 0 :(得分:8)

#define STUDENT(name, grade) { #name, grade }

然后Student John = STUDENT(John, 'A');会扩展为

Student John = { "John", 'A' };

答案 1 :(得分:2)

#include <stdio.h>

typedef struct student
{
    char name[40];
    char grade;
}Student;

#define STUDENT(name, grade) (Student){ #name, *#grade }

int main(){
    Student John = STUDENT(John, A); 

    printf("%s, %c\n", John.name, John.grade);
    return 0;
}