简体   繁体   English

这个litle程序如何工作?

[英]How does this litle program work?

I tried to check QA exercices about C++ and one question drove me crazy !! 我试图检查关于C ++的QA练习,一个问题让我抓狂!

typedef struct {
    unsigned int i : 1;
} myStruct;

int main()
{
    myStruct s;
    s.i = 1;
    s.i++;
    cout << s.i;
    return 0;
}

The question said what is the ouput : 0/1/2/3/-1/Seg Error ? 问题是什么是输出:0/1/2/3 / -1 /段错误?

I did check 2 which is a wrong answer :D , so why does the program shows 0 ? 我确实检查了2这是一个错误的答案:D,那么为什么程序显示为0

You need to familiarize yourself with bitfields . 您需要熟悉位域

By default int has size of 32 bits(4 bytes). 默认情况下,int的大小为32位(4字节)。 But using the given notation, you can specify how many bits are used for the variable. 但是使用给定的表示法,您可以指定变量使用的位数。

So when you increment the value from 1, it overflows and returns to zero. 因此,当您将值从1递增时,它会溢出并返回到零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM