C language-struct (struct) bit field (:) Detailed explanation

Source: Internet
Author: User

struct (struct) bit field (:) Detailed explanation


This address: http://blog.csdn.net/caroline_wendy/article/details/26722511


structures (structs) can use bit fields (:), saving space, for example, with the following code,

In struct A, the first variable x occupies 1 characters, y occupies 2 characters, and Z occupies 33 characters (out of bounds);

However, sizeof () will take the initiative to make up, such as X+y occupies a total of 4 bytes, Z occupies 8 bytes, so the structure occupies 12 bytes;

When the addition operation is used, it is initialized to 0;


Code:

/* * test.cpp * *  Created on:2014.05.23 *      author:spike *//*eclipse CDT, gcc 4.8.1*/#include <iostream> #inc Lude <stdio.h>using namespace std;struct a {int x:1;int y:2;int z:33;}; int main () {a d;cout << &d << std::endl;d.z = d.x + d.y;printf ("%d%d%d%d\n", D.x, D.y, d.z, sizeof (d)); r Eturn 0;}

Output:

0X22FED40 0 0 12




Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

C language-struct (struct) bit field (:) Explain in detail

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.