Union in the C language

Source: Internet
Author: User

1. Multiple members can be defined in union, and the size of the Union is determined by the size of the largest member.
2. Union members share memory of the same block size, only one member can be used at a time, in stark contrast to the struct.
3. Assigning a value to a member overrides the values of other members (not surprisingly, because they share a piece of memory.) but only if the member has the same number of bytes, when the number of bytes of the member does not only overwrite the value on the corresponding byte, such as assigning a value to a char member will not overwrite the entire int member, because Char occupies only one byte and int is four bytes.

4. The order in which the Union union is stored is that all the members are stored from the low address.
Let's look at a simple code:

#include <sctdio.h>typedef union{CharC; intA; intb;} Demo;intMainintargcChar**argv)        {Demo D; D.C='a'; D.A=Ten; D.B= A; printf ("Size:%d\n",sizeof(d));//printf ("%d\n", D.C);printf"%c\t%d\t%d\n", D.C, D.A, D.B); return 0;}

Resources:

Http://www.programlife.net/union-struct-in-c.html

http://blog.csdn.net/huqinwei987/article/details/23597091

Union in the C language

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.