Effect of partial or no intialisation of structure instance variables
Run Output
Aluminium, 20, 302.25
Wood, 0, 400
struct Furniture { char material[40]; int weight;};
This structure will be used as a nested item in structure following next
struct Table { Furniture furn; float price;};
Here Table structure has Furniture structure nested into it. Additional variable price is also defined.
Table round_table={{“Wood”,20}},
The item round_table which is an instance of Table has been partially initialised. round_table.furn.material will become “Wood”, round_table.furn.weight will become 20. The value round_table.price will become 0 as it has not been initialised.
study_table={{“Wood”},400};
More partial initialisation has been done here with study_table.furn.material becoming “Wood”. study_table.furn.weight will become 0 as it has not been initialised. and study_table.price will become 400.
strcpy(round_table.furn.material,”Aluminium”);
Value in round_table.furn.material has been updated to “Aluminium” so the initial value will be changed.
round_table.price=302.25;
This value will also be updated to given value 302.25 as against 0 which was initially set.
cout<<round_table.furn.material<<“, “<<round_table.furn.weight<<“, “
<<round_table.price<<endl;
The values of round_table are printed here.
cout<<study_table.furn.material<<“, ” <<study_table.furn.weight<<“, “
<<study_table.price<<endl;
The values of study_table are printed here. Notice that study_table.furn.weight will print 0 as its value was never updated later.
Notes
- Partial initialisation leads to initialisation with 0 or null as the case may be while if nothing is initialised junk values will result. This effect can be studied further from #2799