Learn point C language (28): Data type

Source: Internet
Author: User
Tags printf

In a structure, the data type of each field is unique; Using unions, you can store different data types in one field.

Different data types share a piece of memory. Of course, its memory size should be based on the big.

The data in the joint, either or, only one is valid; There should be a description of what type is useful at this time in a data.

In addition to shared memory, federation is the same as structure.

1. The size of the union is the size of the largest data member:

#include <stdio.h>

int main(void)
{
  union MyUnion {
    short n1;
    int  n2;
    double n3;
  };

  printf("%u, %u\n", sizeof(union MyUnion), sizeof(double));

  getchar();
  return 0;
}

2. Union is characterized by shared memory, which modifies one other variable:

#include <stdio.h>
#include <limits.h>

int main(void)
{
  union MyUnion {
    unsigned char   n1;
    unsigned short  n2;
    unsigned int   n3; 
  } U = {0};

  printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);

  U.n2 = USHRT_MAX;
  printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);

  U.n3 = INT_MAX;
  printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);

  U.n1 = 0;
  printf("%10u, %10u, %10u\n", U.n1, U.n2, U.n3);

  getchar();
  return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.