Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct initialization of a struct in C

Tags:

c

struct

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

like image 908
knowledge Avatar asked May 12 '15 12:05

knowledge


People also ask

How do you initialize a struct in C?

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.

What is direct initialization?

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.

Can you initialize in struct?

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.

What is struct initialization?

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 ( = ).


1 Answers

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.

like image 157
ouah Avatar answered Oct 20 '22 02:10

ouah