Reputation: 63
I've been searching and can't find anything. Consider this structure
typedef struct student
{
char name[40];
char grade;
}Student;
how do I make a macro for initializing a structure with parameters? Something along the lines of
Student John = STUDENT(John, A);
where STUDENT is a defined macro
Upvotes: 6
Views: 8642
Reputation: 40145
#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;
}
Upvotes: 2
Reputation: 18399
#define STUDENT(name, grade) { #name, grade }
Then Student John = STUDENT(John, 'A');
would be expanded into
Student John = { "John", 'A' };
Upvotes: 9