what is the difference between structure & union
difference between structure & union
Collapse
X
-
A quick google search told me that you've asked the same question on another forum and have been answered.Originally posted by npd1what is the difference between structure & union
If you are still not clear about it then read the following :
http://bobobobo.wordpr ess.com/2008/01/25/c-difference-between-struct-and-union/ -
every data member in union uses the same memory location,thats why it is better option to save the memory.but we can use only one data member at a time.Comment
-
I guess most of the confusion comes when designers include unions as fields along with base types and structs in a new type definition. There seems to be no concern for the storage, just the convenience of hiding the details.Originally posted by santoshramanchaevery data member in union uses the same memory location,thats why it is better option to save the memory.but we can use only one data member at a time.Comment
-
hey dwurmfeld,Originally posted by dwurmfeldI guess most of the confusion comes when designers include unions as fields along with base types and structs in a new type definition. There seems to be no concern for the storage, just the convenience of hiding the details.
could you please give an example of the scenario you've mentioned?Comment
-
Sure, here is a piece of nonsense code, using a formal CoordinateClass would make more sense, but from the point of view of the argument, the union of structures doesn't much help "save space", indeed, if this were an embedded application, could you really trust the sizeof operator?Originally posted by satchhey dwurmfeld,
could you please give an example of the scenario you've mentioned?
Code:#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { typedef struct { double x; double y; int imaginary; } TComplex; typedef struct { double x; double y; } TwoD; typedef struct { TwoD base2D; double z; } ThreeD; union UniversalCoordinate{ TComplex CoordComplex; TwoD Coord2D; ThreeD Coord3D; }; // use the union UniversalCoordinate fred; fred.CoordComplex.x = 0.0; fred.CoordComplex.y = 3.14; fred.CoordComplex.imaginary = -3; fred.Coord2D.x = fred.CoordComplex.x; fred.Coord2D.y = fred.CoordComplex.y; fred.Coord3D.base2D.x = fred.CoordComplex.x; cout << "The Ycoordinate is: " << fred.Coord3D.base2D.y << endl; system("PAUSE"); return EXIT_SUCCESS; }Comment
Comment