Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a struct using a macro

Tags:

c

macros

struct

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

like image 594
dimitrov.l Avatar asked Jul 24 '14 06:07

dimitrov.l


People also ask

Can you initialize a struct?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

How do you initialize a macro?

Initialization macros are invoked from the command line by using the --macro callExpr(args) command. This registers a callback which the compiler invokes after creating its context, but before typing the argument to --main . This then allows configuring the compiler in some ways.

Can you initialize variables in a struct C?

An important thing to remember, at the moment you initialize even one object/ variable in the struct, all of its other variables will be initialized to default value. If you don't initialize the values in your struct, all variables will contain "garbage values".


1 Answers

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

Then Student John = STUDENT(John, 'A'); would be expanded into

Student John = { "John", 'A' };
like image 168
keltar Avatar answered Sep 30 '22 20:09

keltar