Reputation: 1015
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
Upvotes: 7
Views: 1997
Reputation: 919
I would suggest that to try :)
struct person
{
float salary;
int age;
char name[20];
};
int main(){
struct person person1={21,25000.00,"Rakibuz"};
printf("person name: %s \n",person1.name);
printf("person age: %d\n",person1.age);
printf("person salary: %f\n",person1.salary);
}
Upvotes: 0
Reputation: 145829
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.
Upvotes: 7