how should i initialize a struct in c?

Is one way preferred over the other one?

Note: C defines the first as initialization, the 2nd as assignment.

Yes, global object can be initialized, but not assigned with global code.

// Possible
Book romeo = {"Romeo & Juliet", "Shakespeare", 1600};

Book inferno;

// Not possible outside a function.
inferno.title = "Divine Comedy"; = "Dante";
inferno.year = 1400;

is there any way to specify the variable name in the first method

Since C99, members can be specified in any order, complete or not.

Book romeo = {. title = "Romeo & Juliet", .author = "Shakespeare", .year = 1600};
Book romeo = {.year = 1600, . title = "Romeo & Juliet", .author = "Shakespeare" };
Book romeo = {. title = "Romeo & Juliet", .author = "Shakespeare" };  // .year takes on value 0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top