Reputation: 1764
Is there a suggested way on how to initialize a struct in C? For example:
Book romeo = {"Romeo & Juliet", "Shakespeare", 1600};
Book inferno;
inferno.title = "Divine Comedy";
inferno.author = "Dante";
inferno.year = 1400;
Is one way preferred over the other one? I would think for readability the second one is easier, but if there are a ton of fields it might become unwieldy. Additionally, is there any way to specify the variable name in the first method, something like:
Book romeo = {title="...", author="...", year="...");
Upvotes: 0
Views: 72
Reputation: 11
Yes, there's a way but not exactly as you said.
#include <stdio.h>
typedef struct { int k; int l; int a[2]; } T;
typedef struct { int i; T t; } S;
T x = {.l = 43, .k = 42, .a[1] = 19, .a[0] = 18 }; // x initialized to {42, 43, {18, 19} }
int main(void)
{
S l = { 1, // initializes l.i to 1
.t = x, // initializes l.t to {42, 43, {18, 19} }
.t.l = 41, // changes l.t to {42, 41, {18, 19} }
.t.a[1] = 17 // changes l.t to {42, 41, {18, 17} }
};
printf("l.t.k is %d\n", l.t.k); // .t = x sets l.t.k to 42 explicitly
// .t.l = 41 would zero out l.t.k implicitly
}
Moreover, you should visit this once and please check here before you ask a question.
Upvotes: 1
Reputation: 153348
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";
inferno.author = "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
Upvotes: 1
Reputation: 821
Additionally, is there any way to specify the variable name in the first method, something like:
hope below code helps
#include<stdio.h>
typedef struct Book {
char *title;
unsigned int year;
} Book;
int main()
{
Book B1 = { .year = 1999};
Book B2 = {.title= "Jason Bourne", .year = 1999};
printf("B1.year = %d\n", B1.year);
printf("B2.title = %s B2.year = %d\n", B2.title, B2.year);
return 0;
}
Upvotes: 2