I have:
struct date
{
int day;
int month;
int year;
};
struct person {
char name[25];
struct date birthday;
};
struct date d = { 1, 1, 1990 };
Initialization with
struct person p1 = { "John Doe", { 1, 1, 1990 }};
works.
But if I try
struct person p2 = { "Jane Doe", d};
I get an error like:
"Date can't be converted to int".
Whats wrong? d is a struct date and the second parameter should be a struct date as well. So it should work. Thanks and regards
Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and non-explicit user-defined conversion functions, while direct-initialization considers all constructors and all user-defined conversion functions.
You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
struct person p2 = { "Jane Doe", d};
It can be declared this way only if the declaration is at block scope. At file scope, you need constant initializers (d
is an object and the value of an object is not a constant expression in C).
The reason for this is that an object declared at file-scope without storage-class specifier has static storage duration and C says:
(C11, 6.7.9p4) "All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals."
At block-scope without storage class specifier, the object has automatic storage duration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With