what is the difference between structure & union
difference between structure & union
Collapse
X
-
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
-
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
-
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
-
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