In the following example,I've illustrated this using two structures test1
and test2
.The first has two elements-an integer array sized two,and a float element.The second structure has 3 elements,2 integers and one float.
I initialize two structure variables s1 and s2 for test1 as:
s1={{23,52},2.5},s2={21,19,3.6};
Both work fine even though for s2 I have taken out the braces that enclose the array elements.It works fine without warning and output is correct.But when I initialize 2 variables for test2 as follows:
v1={{23,52},2.5},v2={21,19,3.6};
I get incorrect output when I try to print out values of v1 and these are the warnings that I had got upon compilation:
warning: braces around scalar initializer|
warning: (near initialization for 'v1.list1')|
warning: excess elements in scalar initializer|
warning: (near initialization for 'v1.list1')|
||=== Build finished: 0 errors, 4 warnings ===|
Based on this premise,please clear the following doubt that arise:
Question: If using v1={{23,52},2.5}
instead of v1={23,52,2.5}
confuses the compiler about whether the first 2 numbers are distinct integer elements of the structure or part of an integer array element of the structure,then why doesn't using s2={21,19,3.6}
instead of s2={{21,19},3.6}
confuse the compiler into thinking that the structure varialbe s2 has 3 elements (2 integer elements and one float),instead of 2 elements (one integer array of size 2 and a float)?What I especially want to understand is why is the first case about v1's initialization wrong.
#include<stdio.h>
struct test1{
int list[2];
float rate;
}s1={{23,52},2.5},s2={21,19,3.6}; //Works fine
struct test2{
int list1;
int list2;
float rate;
}v1={{23,52},2.5},v2={21,19,3.6}; //Messes things up
int main(void)
{
printf("%d,%d,%f\n",s1.list[1],s2.list[1],s2.rate);
printf("%d,%d,%f\n",v1.list1,v1.list2,v1.rate);
}