Effect of partial or no intialisation of structure instance variables
Understanding default values in case of partial or no initialisation of structure instances.
Learning Objectives
- Partial initialisation of variables of a structure when its instance/object is created.
- No initialisation leads to junk values.
Source Code
|
Run Output
Code Understanding
struct Book { int ID; char name[50]; int year; float price;};
Structure named Book declared with corresponding variables.
//Book b1={1,”Freedom at midnight”,1975,200.25};
This full initialisation example already discussed code sample at #2795 This is commented here in this example.
Book b1={1};
Partial initialisation example with only first value initialised, other are left for default initialisation. Default initialisation is all primitive data type of numbers will be made 0 and char and char array will become null.
/*
Book b1={1,”Freedom at midnight”};
Book b1={1,”Freedom at midnight”,1975};
*/
These are other partial initialisation example. Remember that only trailing variables can be left un-initialised means if third variable is initialised you should not leave the first and second one.
cout<<b1.ID<<” “<<b1.name <<” “<<b1.year<<” “<<b1.price<<endl;
You will see that ID as initialised will be printed while name will not print as it is initialised with null while year and price will be printed as 0.
Book b2;
This is case where another instance has been created but not initialised.
cout<<b2.ID<<” “<<b2.name <<” “<<b2.year<<” “<<b2.price<<endl;
Here junk values will be printed.
Notes
- There is a syntax for all default initialisation. This is –
Book b1={ };
Putting curly braces does the whole trick.
Common Errors
- Sometimes students try to intialise the intermediate initialisation assuming that it will work like this –
Book b1={,”Freedom at midnight”,,200.25};
This won’t work.
Suggested Filename(s): str-part-init.cpp,stprtini.cpp
sunmitra| Created: 19-Jan-2018 | Updated: 19-Jan-2018|