A structure type is defined as:
typedef struct student{
int id;
char* name;
double score;
} Student;
I construct a variable of type
Can I avoid assigning values individually?
You can if the values are already part of a similar struct
, that is, you can do this:
Student s1 = {.id = id, .name = name, .score = score};
which creates an instance of Student
and initializes the fields you specify. This probably isn't really any more efficient than assigning values individually, but it does keep the code concise. And once you have an existing Student
instance, you can copy it with simple assignment:
Student s2;
s2 = s1; // copies the contents of s1 into s2
If the values are all in separate variables and you're not initializing the Student
, then you'll probably need to assign the values individually. You can always write a function that does that for you, though, so that you have something like:
setupStudent(s3, id, name, score);
That'll keep your code short, ensure that the struct is populated the same way every time, and simplify your life when (not if) the definition of Student
changes.