C Tutorial/Data Type/Union

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Output both value in a union

<source lang="cpp">#include <stdio.h> union number {

  int x;
  double y;

}; int main() {

  union number value; 
  value.x = 100; 
  printf( "%s\n%s\n%s%d\n%s%f\n\n",
     "Put a value in the integer member",
     "and print both members.",
     "int:   ", value.x,
     "double:\n", value.y );
  value.y = 100.0;
  printf( "%s\n%s\n%s%d\n%s%f\n",
     "Put a value in the floating member",
     "and print both members.",
     "int:   ", value.x,
     "double:\n", value.y );
  return 0;

}</source>

Put a value in the integer member
and print both members.
int:   100
double:
0.000000
Put a value in the floating member
and print both members.
int:   0
double:
100.000000

Union

  1. Union has members of different data types, but can hold data of only one member at a time.
  2. The different members share the same memory location.
  3. The total memory allocated to the union is equal to the maximum size of the member.


<source lang="cpp">#include <stdio.h> union marks {

   float percent;
   char grade;

}; int main ( ) {

   union marks student1;
   student1.percent = 98.5;
   printf( "Marks are %f   address is %16lu\n", student1.percent, &student1.percent);
   student1.grade = "A";
   printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade);

}</source>

Marks are 98.500000   address is          2293620
Grade is A address is          2293620