Direct structure initialization in C

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 }}; 

work.

But if I try

 struct person p2 = { "Jane Doe", d}; 

I get an error message:

"Date cannot be converted to int."

What's wrong? d is the date of the structure, and the second parameter should also be the structure. So that should work. Thank you and welcome

+7
c struct
source share
1 answer
 struct person p2 = { "Jane Doe", d}; 

It can be declared this way only if the declaration is in the block area. In the file area, you need constant initializers ( d is an object, and the value of the object is not a constant expression in C).

The reason for this is because an object declared in a file area without a storage class specifier has a static storage duration, and C says:

(C11, 6.7.9p4) "All expressions in the initializer for an object that has a static or storage duration of streams should be constant expressions or string literals."

In a block space without a storage class specifier, an object has an automatic storage duration.

+6
source share

All Articles